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)