DEV Community

Cover image for How to make interfaces optional in typescript
Tofail Ahmed Sayem
Tofail Ahmed Sayem

Posted on

How to make interfaces optional in typescript

First of all let us look at some random example,



interface personMale{
      gender:"male";
      salary:number;
}
interface personFemale{
      gender:"female";
      weight:number
}
type person={
      name:string;
      age:number;


}&(personMale|personFemale)


const person1:person={
      name:"Sayem",
      age:27,
      gender:"male",
      salary:0
}
const person2:person={
      name:"Setara",
      age:24,
      gender:"female",
      weight:55
}

Enter fullscreen mode Exit fullscreen mode

Here we should use "male" and "salary" together and "female" and " "weight" together. If we want to use "male" and "weight" or "female" and "salary" together, it will through error.

In Typescript, we can define optional properties in an interface by adding a question mark (?) to the property name. This tells Typescript that this property may or may not exist on the object.

As mentioned earlier, the basic way to make a property optional is by appending a question mark(?) to the property name. Here is an simple example,

interface User {
  id: number;
  name?: string;
  email?: string;
}


let user: User = { id: 1 };

Enter fullscreen mode Exit fullscreen mode

In the above example, name and email are optional. If we create an object named ‘user’ with only ‘id’ property Typescript will not complain.

Using utility type:
Typescript provides several utility types to manipulate types, another being Partial, which makes all properties in a type T optional. Here’s how we can use it,

interface User {
  id: number;
  name: string;
  email: string;
}


type OptionalUser = Partial<User>;


let user: OptionalUser = { id: 1 };

Enter fullscreen mode Exit fullscreen mode

In the above example, OptionalUser is a new type where all properties of User are optional. Hence, we can assign an object with only the id property to the user.

Top comments (0)