问题
这篇文章底部的TypeScript导致以下错误:
类型"{title:string;outline:"上不存在属性"push"一串为什么:字符串;additional:string;}'。ts(2339(
我理解错误发生的原因,只是不知道如何解决。理想情况下,我会将idea
密钥从可能的密钥列表中排除,但我不确定如何解决。
TypeScript
type Idea = {
challenges: Array<string>,
personas: Array<string>,
experiences: Array<string>,
idea: {
title: string,
outline: string,
why: string,
additional: string,
}
};
let idea:Idea = {
challenges: [],
personas: [],
experiences: [],
idea: {
title: "",
outline: "",
why: "",
additional: "",
}
};
function addtoIdea(ideaItem:string, uniqueId:string){
idea[ideaItem as keyof typeof idea].push(uniqueId);
}
addtoIdea("challenges","abcd1234");
正如我的评论中所提到的,您需要首先确保您尝试push
进入的属性是Array
:
type Idea = {
challenges: Array<string>,
personas: Array<string>,
experiences: Array<string>,
idea: {
title: string,
outline: string,
why: string,
additional: string,
}
};
let idea:Idea = {
challenges: [],
personas: [],
experiences: [],
idea: {
title: "",
outline: "",
why: "",
additional: "",
}
};
function addtoIdea(ideaItem:string, uniqueId:string){
const prop = idea[ideaItem as keyof typeof idea]; // string[] | { ... }
if(Array.isArray(prop)){
prop.push(uniqueId); // prop is string[]
}
}
addtoIdea("challenges","abcd1234");
工作操场