Borislav Hadzhiev
Sat Mar 19 2022·2 min read
Photo by Stephen Cook
To make all of the properties of a type optional except one, use an interface
to extend the type passing it to the Partial
utility type, e.g.
interface OptionalExceptSalary extends Partial<Employee> {}
and override the
specific property setting it to required.
interface Employee { id: number; name: string; salary: number; } interface OptionalExceptSalary extends Partial<Employee> { salary: number; } const emp: OptionalExceptSalary = { salary: 100, };
We used the Partial utility type to construct a type where all of the properties are set to optional.
interface Employee { id: number; name: string; salary: number; } // 👇️ type Opt = { // id?: number | undefined; // name?: string | undefined; // salary?: number | undefined; // } type Opt = Partial<Employee>;
The only properties we want to override in the new interface are the ones we want to mark as required.
You can achieve the same result by using a type alias.
interface Employee { id: number; name: string; salary: number; } type OptionalExceptSalary = Partial<Employee> & { salary: number; }; const emp: OptionalExceptSalary = { salary: 100, };
You can use this approach to mark all properties except N as optional.
An alternative approach is to create a utility type that makes the specified properties optional.
interface Employee { id: number; name: string; salary: number; } type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> & Partial<Type>; // 👇️ mark salary as optional const emp: MakeOptional<Employee, 'salary'> = { id: 1, name: 'James', };
The MakeOptional
utility types takes a type and one of the type's keys as
parameters and marks the specified key as optional (salary
in the example).
You don't have to only mark a single property as optional.
interface Employee { id: number; name: string; salary: number; } type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> & Partial<Type>; // 👇️ mark salary and name as optional const emp: MakeOptional<Employee, 'salary' | 'name'> = { id: 1, };
The Omit utility constructs a new type by picking all properties from the provided type and removing the specified keys.
interface Employee { id: number; name: string; salary: number; } // 👇️ type T = { // id: number; // name: string; // } type T1 = Omit<Employee, 'salary'>; // 👇️ type T2 = { // id: number; // } type T2 = Omit<Employee, 'salary' | 'name'>;
The first example look something like:
interface Employee { id: number; name: string; salary: number; } // 👇️ type T10 = { // id: number; // name: string; // } & Partial<Employee> type T10 = { id: number; name: string } & Partial<Employee>; // 👇️ only salary is marked as optional const example: T10 = { id: 1, name: 'James', };