【问题标题】:How to inline destructure nested optional properties from an object in Typescript?如何从 Typescript 中的对象内联解构嵌套的可选属性?
【发布时间】:2021-09-13 15:30:46
【问题描述】:

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

“地址”类型上不存在“街道”属性 |未定义'

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

这里 street 在类型 Address | undefined 上不存在

【问题讨论】:

    标签: javascript typescript typescript-typings typescript2.0


    【解决方案1】:

    您需要在您的const 中初始化address。

    像这样:

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

    PlaygroundLink

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 2017-09-10
      • 2021-07-14
      • 2020-08-27
      相关资源
      最近更新 更多