Here is how object destructuring is done in JavaScript.
const player = {
firstName: 'Roger',
lastName: 'Federer',
age: 36,
};
const { firstName, lastName } = player;
console.log(firstName); // Roger
console.log(lastName); // Federer
What about if we want to apply types to this for use in TypeScript?
const { firstName, lastName }: { firstName: string; lastName: string } = player;
console.log(firstName); // Roger
console.log(lastName); // Federer
We can shorten and simplify this by creating a type
or interface
for what we are destructuring, which are the firstName
and lastName
in this case.
const player = {
firstName: 'Roger',
lastName: 'Federer',
age: 36,
};
interface PlayerName {
firstName: string;
lastName: string;
}
const { firstName, lastName }: PlayerName = player;
console.log(firstName); // Roger
console.log(lastName); // Federer