Optional properties are a powerful feature in TypeScript that allow developers to create flexible and reusable interfaces or types. They enable the definition of properties that may or may not be present in an object, providing greater versatility in object structures.
To declare an optional property in TypeScript, simply add a question mark (?
) after the property name. This syntax informs the compiler that the property is not required and may be omitted without causing type errors.
interface User {
name: string;
age?: number; // Optional property
email: string;
}
In this example, age
is an optional property, while name
and email
are required.
Optional properties are particularly useful in scenarios where:
function createUser(name: string, email: string, age?: number) {
return { name, email, age };
}
const user1 = createUser("Alice", "alice@example.com");
const user2 = createUser("Bob", "bob@example.com", 30);
In this example, the age
parameter is optional, allowing the function to be called with or without specifying an age.
undefined
values when accessing optional propertiesWhile optional properties use the ?
syntax, they can be combined with Union Types for more granular control:
interface Product {
name: string;
price: number;
discount?: number | "none";
}
In this case, discount
is optional and can be either a number or the string "none" when present.
When working with optional properties, it's crucial to perform proper type checking to avoid runtime errors:
function applyDiscount(product: Product) {
if (product.discount !== undefined && typeof product.discount === "number") {
return product.price * (1 - product.discount);
}
return product.price;
}
This function safely handles the optional discount
property, ensuring type safety and preventing potential errors.
Optional properties in TypeScript provide a flexible way to define object shapes, allowing for more adaptable and reusable code. By understanding and utilizing this feature effectively, developers can create more robust and maintainable TypeScript applications.
For more advanced type manipulations, consider exploring TypeScript Utility Types, which offer powerful tools for working with optional and required properties.