optional chaining
The operator written (?.) that reads a property or calls a method only if the value before it is not null or undefined.
In more detail
req.user?.role gives undefined instead of crashing when user is missing. It is JavaScript syntax from ES2020 that TypeScript understands and narrows correctly.
Example
const role = req.user?.role ?? "anonymous";Related terms
- nullish coalescing — The double question mark operator (??), which gives a fallback value only when the left side is null or undefined.
- null — A special value meaning no value or no object, set on purpose to show that something is empty or absent.
- undefined — The JavaScript value meaning not set: a variable with no value yet, a missing property or a function that returned nothing.
Taught in
- The Compiler Pipeline: tsc, AST And Code Emission — Production TypeScript