Optional Properties
Mark a property as optional with a question mark so it can be omitted.
Syntax
interface User { name: string; nickname?: string; }Add a ? after a property name to make it optional. Objects can then include or leave out that property.
When you access an optional property, its type includes undefined, so TypeScript reminds you to handle the missing case.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A blog post interface marks the subtitle field as optional so posts without subtitles are still valid.
- A function accepting a configuration object uses optional properties to avoid requiring callers to pass every key.
- An API request type marks query parameters as optional since they each have server-side defaults.
More examples
Optional property with ?
Marks subtitle as optional and uses optional chaining to safely call a method only when the value is present.
interface BlogPost {
title: string;
body: string;
subtitle?: string; // may be undefined
}
const post: BlogPost = { title: 'TypeScript Tips', body: 'Content here' };
console.log(post.subtitle?.toUpperCase()); // optional chainingOptional parameter in function
Declares an optional function parameter and applies a default with nullish coalescing when it is omitted.
function createUser(name: string, role?: string): string {
return `${name} (${role ?? 'viewer'})`;
}
createUser('Alice'); // 'Alice (viewer)'
createUser('Bob', 'admin'); // 'Bob (admin)'Accessing optional properties safely
Uses an interface with all optional properties and ?? to supply defaults, a common pattern for options objects.
interface Config {
timeout?: number;
retries?: number;
}
function fetchData(url: string, cfg: Config = {}): void {
const timeout = cfg.timeout ?? 5000;
const retries = cfg.retries ?? 3;
console.log(`${url} timeout=${timeout} retries=${retries}`);
}
Discussion