制作打字稿以允许解构未定义的

时间:2021-02-25 07:09:08

标签: typescript

我正在将我的代码从 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
 
 

此处的打字稿会引发错误,说(例如在电子邮件中)类似这样的内容

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

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

2 个答案:

答案 0 :(得分: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 将拥有两个接口的所有属性。

答案 1 :(得分:0)

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

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;

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