Optional properties let you create flexible interfaces where some properties may or may not be present. This helps when you don't always have all the information.
0
0
Optional properties in interfaces in Typescript
Introduction
When defining a user profile where some details like phone number might be missing.
When creating configuration objects where some settings are optional.
When working with data from APIs that may not return all fields.
When designing functions that accept objects with some optional parameters.
Syntax
Typescript
interface InterfaceName {
propertyName?: propertyType;
}The question mark ? after the property name marks it as optional.
Optional properties can be left out when creating objects of that interface.
Examples
The
age property is optional. You can create a User with or without age.Typescript
interface User {
name: string;
age?: number;
}Both
timeout and debug are optional properties in this configuration interface.Typescript
interface Config {
url: string;
timeout?: number;
debug?: boolean;
}Sample Program
This program shows two Product objects. The first one does not have the optional description. The second one includes it.
Typescript
interface Product {
id: number;
name: string;
description?: string;
}
const product1: Product = {
id: 1,
name: "Book"
};
const product2: Product = {
id: 2,
name: "Pen",
description: "Blue ink pen"
};
console.log(product1);
console.log(product2);OutputSuccess
Important Notes
Optional properties help avoid errors when some data is missing.
When accessing optional properties, you might want to check if they exist first to avoid runtime errors.
Summary
Optional properties are marked with a ? in interfaces.
They allow objects to omit those properties safely.
This makes your code more flexible and easier to work with incomplete data.