The ?
operator in TypeScript is used to define optional values, both for function parameters and object properties. When ?
is used on an object property or function parameter, it means that this value is optional and can be omitted.
Example:
interface Person { name: string; age?: number; } const john: Person = { name: 'John' }; // The 'age' property is optional.
The ?
operator can also be used for handling null
or undefined
types in expressions.
let value: string | undefined; let result = value?.length; // Safe access to 'length' even if value is undefined.
In this example, ?.
is the optional chaining operator, which allows safe access to object properties without worrying about errors if the object is null
or undefined
.