The ? symbol in TypeScript denotes an optional property in an interface. When a property is marked as optional, it means that objects adhering to the interface can either include the property or omit it altogether. This is useful for defining flexible data structures where certain properties are not always required.
In more details, an optional property is one that can either be present or absent in the objects that implement the interface. Optional properties are useful in situations where not all properties are required for the object to be valid.
Syntax
Examples
Basic Example
In this example, the email property is optional, so user1 is a valid User object even without an email.
Optional Properties in Functions
We can define functions that accept objects with optional properties and handle those properties appropriately.
Here, the setup function can handle Config objects with or without the timeout and baseURL properties.
Optional Properties in Union Types
When using union types in interfaces, optional properties can help define more flexible and precise types.
In this example, the radius and sideLength properties are optional, allowing for more flexible shape definitions.
Optional Properties and Default Values
We can use the nullish coalescing operator (??) or logical OR (||) to provide default values for optional properties when they are not provided.
Summary
Optional Properties: Denoted by ?, they allow properties to be omitted in objects implementing an interface.
Syntax: propertyName?: type;
Use Cases: Flexible data structures, functions with optional parameters, and union types.
Handling Optional Properties: Use default values with ?? or || to handle cases where optional properties are not provided.