How to specify type in object destructuring?

Object destructing is a nice way of getting object property as a variable. In TypeScript, we also can do object destructing.

We often run into issues when we try to declare the type when destructing. Let’s consider the following example:

interface User {
    username: string;
    age: number;
    status: string;
}

const obj: User = { username: 'Johnny', age: 25, status: 'active' };

This is how we do the destructing:

const { username, age }: User = obj;
console.log(username, age);
// Output: Johnny 25

But if we try to do the following, TypeScript will complain about the variable.

const { username: string, age: number } = obj;
console.log(username); //  TS2304: Cannot find name 'username'.