How to do object destructuring with types in TypeScript?
Published April 12, 2021
Sometimes when you destructure object properties in TypeScript, you may want to define the type for the property you are destructuring.
TL;DR
// an object
const John = {
age: 23,
isAdult: true,
};
// get age property using destructuring syntax
// and set the type of age property
const { age }: { age: number } = John;
For example, let's say I have an object called John
with some properties like age
, isAdult
like this,
// an object
const John = {
age: 23,
isAdult: true,
};
Now let's use the destructuring operator ({}
curly braces) to get the age
property from the John
object like this,
// an object
const John = {
age: 23,
isAdult: true,
};
// get age property using destructuring syntax
const { age } = John;
To set or define a type on the age property we can use a colon :
after the destructuring operator and then open a curly brace and then define the type of the age
property inside that curly brace like this,
// an object
const John = {
age: 23,
isAdult: true,
};
// get age property using destructuring syntax
// and set the type of age property
const { age }: { age: number } = John;
See the above code live in codesandbox
There is one more way of defining the type using an interface
like this,
// interface for age property
interface Age {
age: number;
}
// an object
const John = {
age: 23,
isAdult: true,
};
// get age property using destructuring syntax
// and set the type using the interface "Age"
const { age }: Age = John;
That's it! 😃