How do I make optional properties truly optional in TypeScript?

Clock Icon

asked about 1 year ago

Message Icon

1

Eye Icon

73

I am working with interfaces in TypeScript, and I want some properties to be optional. However, when I use them later in code, TypeScript still throws errors saying the property might be undefined. What is the right way to deal with optional props in a safe and clean way?

1 Answer

Optional properties must be accessed with care. Either use optional chaining:

1interface User {
2 name: string;
3 age?: number;
4}
5
6const user: User = { name: 'John' };
7console.log(user.age?.toString()); // Safe access
1interface User {
2 name: string;
3 age?: number;
4}
5
6const user: User = { name: 'John' };
7console.log(user.age?.toString()); // Safe access

Or use default values:

1const age = user.age ?? 0;
1const age = user.age ?? 0;

This ensures your code does not crash if the property is undefined.

1

Write your answer here