DEV Community

Jitendra
Jitendra

Posted on

Make properties optional in TypeScript

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"
};
Enter fullscreen mode Exit fullscreen mode

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
};
Enter fullscreen mode Exit fullscreen mode

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
};
Enter fullscreen mode Exit fullscreen mode

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',
};
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

Top comments (0)