Typescript Optional explained

Last update: 2022-12-01
Type
Quick Win's logo Quick Win
Membership
🆓
Tech
TypeScript TypeScript
TypeScript
Share:

In TypeScript, you can use the ? symbol to mark a property or parameter as optional. This means that the property or parameter is not required, and it is okay if it is not provided.

For example, consider the following interface:

interface Person {
	firstName: string;
	lastName: string;
	age?: number;
}

The age property in this interface is marked as optional, so it is okay if an object that implements this interface does not have an age property.

To use an optional property or parameter, you can simply leave it out when you create an object or call a function. For example:

const person: Person = {
	firstName: 'John',
	lastName: 'Doe'
};

console.log(person.age); // undefined

If you do want to provide a value for an optional property or parameter, you can simply include it as you normally would.

const person: Person = {
	firstName: 'John',
	lastName: 'Doe',
	age: 30
};

console.log(person.age); // 30

Optional properties and parameters can be useful when you want to give users the option to provide additional information, but you don’t want to force them to do so.

Keep in mind that if you try to access an optional property that has not been provided, it will have a value of undefined. You may need to check for this value before using the property, or you can use the ! symbol to tell TypeScript that you are sure the property has a value.

const age = person.age!;
Simon Grimm

© 2023 Galaxies.dev. All rights reserved.