DEV Community

loading...
Cover image for How to make Interface properties optional without changing Interface??
This is Angular

How to make Interface properties optional without changing Interface??

Nikhil Dhawan
Updated on ・2 min read

Hey all, we might have come across this situation where we define the Interface but at the time of defining the object out of that we might not able to have the value of all the properties, so at that position what we will use?
Let's start this by taking the example and ways we can achieve it.

interface CustomerDetails{
  firstName: string,
  lastName: string,
  mbNumber: string,
  adress: string
}
firstCustomer:CustomerDetails={
    firstName: 'Nikhil',
    lastName: 'Dhawan'
  }
Enter fullscreen mode Exit fullscreen mode

Here we will get the below error message, which simply means that we don't have all properties

Type '{ firstName: string; lastName: string; }' is missing the following properties from type 'CustomerDetails': mbNumber, address

How we can correct this situation?

The first way which will come to your mind will be making all properties optional like


interface CustomerDetails{
  firstName?: string,
  lastName?: string,
  mbNumber?: string,
  address?: string
}
firstCustomer:CustomerDetails={
    firstName: 'Nikhil',
    lastName: 'Dhawan'
  }
Enter fullscreen mode Exit fullscreen mode

This approach will surely solve our error but we have a more elegant way to handle this rather than going to all interfaces and making the properties optional.


interface CustomerDetails{
  firstName: string,
  lastName: string,
  mbNumber: string,
  address: string
}
  firstCustomer:Partial<CustomerDetails>={
    firstName: 'Nikhil',
    lastName: 'Dhawan'
  }
Enter fullscreen mode Exit fullscreen mode

Here we used Partial<> which helps us to make the properties option for the underlying Interface.

So now if we write in this way we will be able to achieve the same behavior but without modifying our actual interface.

Hope this helped you in learning something new and interesting, if you already knew this, please share it so others can also learn this or if any suggestions reach me out on Twitter or comment below. Till next time Happy Learning.
Do share your feedback.

Discussion (0)