TypeScript映射具有类型的已分解参数给出错误

时间:2019-05-27 02:59:16

标签: typescript destructuring

可以说我有以下对象

const a = {
   history: string[]
}

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

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

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

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

如果我只是删除该类型,然后添加以下内容,则它可以正常工作而不会出现编译问题

const { history: mappedCareerHistory } = a;

1 个答案:

答案 0 :(得分:0)

这是因为您要展开对象而不更改键。

对于Ex

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

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