I just came into a situation where I needed to mark one or more keys optional in a TypeScript interface.
Letโs say that I have an interface of three keys name
, age
, and email
.
interface User {
name: string;
age: number;
email: string
}
// ๐ OK, name, age, and email are defined
const pawel: User = {
name: "Pawel Grzybek",
age: 34,
email: "email@email.com"
};
In today's modern world, if you have a small or large JSON object and want to create an interface for it, don't waste your time doing it manually. You can useย an online JSON to Typescript converter.
Make all properties optional except one in TypeScript
Now I have a case in which I want to assign only name
and age
without email.
interface User {
name: string;
age: number;
email: string
}
// ๐ Uuups, Property 'email' is missing
const pawel: User = {
name: "Pawel Grzybek",
age: 34
};
To handle this situation, TypeScript provides a handy utility type Partial. Which converts all keys to optional.
interface User {
name: string;
age: number;
email: string
}
interface OptionalExceptEmail extends Partial<User> {
email?: string
}
// ๐ OK, all looks good
const pawel: OptionalExceptEmail = {
name: "Pawel Grzybek",
age: 34
};
Make a single or multiple properties optional in Typescript
To solve using best practices in Typescript. I will create another type to make it work.
interface Dev {
language: string;
age: number;
experience: number;
}
type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> &
Partial<Pick<Type, Key>>;
// ๐ mark experience as optional
type T1 = MakeOptional<Dev, 'experience'>;
const dev1: T1 = {
age: 30,
language: 'ts',
};
// ๐ mark experience and age as optional
type T2 = MakeOptional<Dev, 'experience' | 'age'>;
const dev2: T2 = {
language: 'ts',
};
Make all properties optional in TypeScript
To make all properties optional. Again I will use an amazing utility called Partial
.
interface Person {
personId: number;
fullName: string;
annualIncome: number;
}
// ๐ mark all keys as optional
const emp: Partial<Person> = {};
emp.fullName = 'Bobby Hadz';
Top comments (0)