Forem

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay