How to make Interface properties optional without changing Interface??
Nikhil Dhawan
Posted on June 10, 2021
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'
}
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'
}
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'
}
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.
Posted on June 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.