javascripttypescripttypescript-typingstypescript2.0

How to inline destruct nested optional properties from an object in Typescript?


I have the following code of a type User that has optional type Address that I want to desctructure in a single line. However, when I try, I am getting an error saying:

Property 'street' does not exist on type 'Address | undefined'

Click here to see the Typescript playground of the code provided bellow

type User = {
 age: number;
 address?: Address;
}

type Address = {
 street?: string;
}

const user: User = {
 age: 22,
 address: {}
}

const {age, address: {street}} = user

Here the street does not exist on type Address | undefined


Solution

  • You need to initialize the address in your const.

    Like this:

    const {age, address : {street} = {}} = user;
    

    PlaygroundLink