Sometimes, we want to add TypeScript types in object destructuring.
In this article, we’ll look at how to add TypeScript types in object destructuring.
How to add TypeScript types in object destructuring?
To add TypeScript types in object destructuring, we can add the type after the colon.
For instance, we write
interface User {
name: string;
age: number;
}
const obj: any = { name: "jane", age: 25 };
const { name, age }: User = obj;
to create the User
interface.
And then we set it as the type of obj
on the last line by putting User
after the colon.
Then name
and age
will be assign the type of string
and number
respectively because of the type assignment.
Conclusion
To add TypeScript types in object destructuring, we can add the type after the colon.