结合使用 Javascript 和 Typescript (v1.4.1) 我有一个自定义类型,如下所示:
interface WordDataForQuestion {
question : {
id : number;
vocab : string;
comment : string;
};
possibleAnswers : {
[index : number] : {
id : number;
vocab : string;
comment : string;
}
};
}
现在我想推送数组中的一个元素possibleAnswers
nextWordData.possibleAnswers.push(
{
id : vocabs[index].id,
vocab : vocabs[index].voc_t,
comment : vocabs[index].com_t
}
);
但它给了我以下错误:
exercise.ts(69,42): error TS2339: Property 'push' does not exist on type '{ [index: number]: { id: number; vocab: string; comment: string; }; }'.
我不明白出了什么问题 - possibleAnswers
应该是一个支持推送操作的 JavaScript 数组。难道我说的不对吗?
最佳答案
你就快到了。您确实将其定义为带有索引器的对象。不是数组,请参见下面的示例
possibleAnswers : {
id : number;
vocab : string;
comment : string;
}[];
关于javascript - Typescript:推送在自定义类型数组上不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28125758/