【问题标题】:typescript mapping destructured parameter with type gives error带有类型的打字稿映射解构参数给出错误
【发布时间】:2019-10-12 14:56:05
【问题描述】:

假设我有以下对象

const a = {
   history: string[]
}

现在我正在尝试将历史使用分配给另一个变量 historyMapped,同时给出对象类型 (string[])。

const { history: mappedCareerHistory }: { mappedCarerHistory: string[] } = a;

但是我在这里遇到以下错误

类型中缺少属性 mappedHistory.....

如果我只是删除类型然后包含以下内容,则它可以在没有编译问题的情况下工作

const { history: mappedCareerHistory } = a;

【问题讨论】:

    标签: typescript destructuring


    【解决方案1】:

    这是因为您正在解包对象而不是更改密钥。

    前任

    let a = {history:['1','2']};
    const {history: mappedCareerHistory} = a;
    console.log(mappedCareerHistory); // ["1", "2"];    
    

    您没有更改对象的键,而是解包对象,因此编译器会出错。所以类型必须是字符串数组而不是映射对象类型。

    【讨论】:

    • 以你上面的例子,那么我如何给 mappedCareerHistory 一个类型?
    • 你能具体说明你想要什么行为吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2017-09-29
    • 2017-01-10
    相关资源
    最近更新 更多