Typescript : Defining types for destructured objects

Typescript : Defining types for destructured objects

Defining types when destructuring objects in typescript seems a bit confusing for beginners. So in this short article, I'll attempt to explain this concept in an easy and understandable way.

Let's say we have an object

const user = { firstname: 'John', lastname: 'Doe', age: 25 }

Javascript destructuring feature allows us to conveniently extract specific properties from our object based on our needs. Like so

const {firstname, age} = user;
// we can now use variables 'firstname' and 'age' like any other normal variable.
// console.log(firstname, age)   John  25

That said, how do we go about defining the type of the destructured object?

We might want to do something like this

const {firstname: string, age: number } = user;
//But this renames the variable 'firstname' to 'string' and 'age' to 'number'
console.log(firstname) // error -- firstname is not defined
console.log(string) // John

also if we have two variables of the same type, then we hit an error.

//error, since we are redefining the 'string' variable.
const {firstname: string, lastname: string, age: number } = user; 

//This is becasue when we destructure an object, we can rename properties with variables like so;
const {firstname: myfirstname, lastname: mylastname, age: myage } = user;

Therefore to define these types, we have to assign them after the destructuring. Like this :

const { firstname, age }: { firstname: string, age: number } = user;
// Please note that we can still rename our variables and we must make sure to use the types for the original names.
const {
  firstname: myfirstname,
  age: myAge,
}: { firstname: string, age: number } = user;

At this point, we can make use of either type aliases or interfaces to make out code more pretty and concise.

interface PersonInterface {
  firstname: string;
  age: number;
}
const { firstname, age }: PersonInterface = user;

The example illustration below attempts to solidify our understanding of the above-mentioned concept.

Destructuring of objects and passing them as function arguments is a very common pattern in react when used with typescript. I'm hopeful that the above discussion may come in handy the next time you decide to use it.