如何从 Typescript 中的对象内联解构嵌套的可选属性?

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

我有以下 User 类型的代码,它具有可选类型 Address,我想在一行中对其进行解构。但是,当我尝试时,我收到一条错误消息:

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

此处 街道 在类型 Address | undefined

上不存在

您需要在 const 中初始化 address

像这样:

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

PlaygroundLink