TypeScript Optional Properties
An optional property is a property marked with a question mark in a type. An object of that type may leave the property out.
Leave a property out
The age property is optional. The object compiles without it.
interface User {
name: string;
age?: number;
}
const user: User = { name: "Ada" };
console.log(user.name);
console.log(user.age);Check before use
The function checks age before it uses the value. One object has an age and one does not.
interface User {
name: string;
age?: number;
}
function showAge(user: User): void {
if (user.age !== undefined) {
console.log(user.name + " is " + user.age);
} else {
console.log(user.name + " has no age listed");
}
}
const ada: User = { name: "Ada", age: 36 };
const ben: User = { name: "Ben" };
showAge(ada);
showAge(ben);Example
interface Profile {
username: string;
bio?: string;
website?: string;
}
const first: Profile = { username: "ada", bio: "Mathematician" };
const second: Profile = { username: "ben" };
console.log(first.username);
console.log(first.bio);
console.log(second.bio);
console.log(second.website);Key points
- A question mark after a property name makes that property optional.
- An optional property still holds its named type when a value is given.
- Reading an absent optional property gives undefined.
- A check against undefined makes an optional value safe to use.
- Required properties must still appear in every object of the type.
In this example, the Profile type has one required property and two optional properties. The first object gives a bio and leaves the website out. The second object gives only the username. Reading the missing properties gives undefined.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does a question mark after a property name mean?