【问题标题】:make typescript to allow destructuring of undefined制作打字稿以允许解构未定义
【发布时间】:2021-05-27 12:54:54
【问题描述】:

我正在将我的代码从 JS 迁移到 TS。

现在,我的组件接受对象数组,每个对象都依赖于键

interface a {
 name?: string 
 lastName?: string 
}

interface b {
 email?: string 
 phone?: number 
}


const options:a | b = {email: 'itzrahulpatel@outlook.com'}

const {
 email, 
 phone, 
 name, 
 lastName 
} = options
 
 

Typescript 在这里抛出一个错误,说(比如在电子邮件中)这样的事情

Property 'name' does not exist on type 'b'
Property 'lastName' does not exist on type 'b'

知道如何修复此类错误吗?我稍后在我的代码中处理了未定义的事情(这不是实际代码,只是一个示例代码)。

【问题讨论】:

  • 更多关于{...something}sn-p的细节
  • @C-lioGarcia 完成
  • 您能否将您的解决方案发布给可能面临同样问题的人?
  • const options: a & b = {email: 'itzrahulpatel@outlook.com'} 成功了

标签: typescript


【解决方案1】:

您在此处使用type union,这意味着options 将仅定义ab 共有的属性。

例如,如果:

interface a {
    name: string;
    lastName: string;
}

interface b {
    name: string;
    age: number;
}

const options: a | b;

那么options 将只定义name 属性。

在您的情况下,ab 之间没有任何共同点,因此 options 实际上是一个“空”接口;

你需要的是type intersection

如果你定义为

const options: a & b = {}

那么options 将拥有两个接口的所有属性。

【讨论】:

  • 我也这么认为,但是 ir 好像只有在 OPs 示例中允许的 a 类型的属性。如果接口为空,则不应允许任何属性,但在解构中允许a 的属性。另一方面,使用const options: a & b = {},这对我来说非常有意义,我得到了错误:Cannot redeclare block-scoped variable 'name'.(2451)
  • @rustyBucketBay 我也遇到过。将属性名称更改为name1,问题就消失了,一切正常。
  • ¯\_(ツ)_/¯ 可能是 Typescript Playground 的运行方式...
  • 与这个问题无关。如果您只是简单地执行const name = 'John';,则会获得相同的错误。找到解释here :)
  • 感谢@rustyBucketBay 的澄清!
【解决方案2】:

据此,我的解决方案可能是:

interface a {
        name?: string 
        lastName?: string 
    }
       
       interface b {
            email?: string 
            phone?: number 
       }

       const something:a | b = {
           name: "Célio",
           lastName: "Garcia",
           email: "cgarcia@celiogarcia.com",
           phone: 92100000
       }

       const options:a & b = {...something}

const {
 email, 
 phone, 
 name, 
 lastName 
} = options;

希望对遇到此问题的人有所帮助。

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2016-11-06
    • 2016-09-05
    • 2021-10-22
    • 1970-01-01
    • 2016-12-13
    相关资源
    最近更新 更多