Two Useful TypeScript Utility Types
By WittCode
Learn two handy TypeScript utility types that make working with types easier.
Table of Contents 📖
Optional Properties
In TypeScript we can denote a property as optional by adding a question mark (?) after the property name. Below, the age property is optional.
type Person = {
name: string;
age?: number;
address: {street: string, city: string};
}
However, there may be times in an application where all the Person attributes are optional or all of them are required. TypeScript makes this easy with the utility types Partial and Required.
Partial and Required
Partial marks all members as optional while Required marks all members as required.
type Person = {
name: string;
age?: number;
address: {street: string, city: string};
}
const partialPerson: Partial<Person> = {};
// Property 'address' is potentially undefined in type 'Partial<Person>'
console.log(partialPerson.address?.city);
// Property 'age' is missing in type '{ name: string; address: { street: string; city: string; }; }' but required in type 'Required<Person>'
const requiredPerson: Required<Person> = {
name: 'John',
address: {street: '123 Main St', city: 'Anytown'},
};