本文介绍了打字稿:推送不适用于自定义类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将Javascript与Typescript一起使用(v1.4.1)我有一个自定义类型如下:
Using Javascript with Typescript (v1.4.1) I have a custom type as follows:
interface WordDataForQuestion {
question : {
id : number;
vocab : string;
comment : string;
};
possibleAnswers : {
[index : number] : {
id : number;
vocab : string;
comment : string;
}
};
}
现在我要推送数组中的元素 possibleAnswers
Now I want to push an element in the array 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
应该是一个支持push-operation的JavaScript数组。我不对吗?
I don't understand what is wrong - possibleAnswers
should be a JavaScript array here which supports the push-operation. Am I not right?
推荐答案
你几乎就在那里。您确实将其定义为具有索引器的对象。不作为数组,请参阅下面的示例
You are almost there. You did define it as an object with an indexer. Not as an array, see example below
possibleAnswers : {
id : number;
vocab : string;
comment : string;
}[];
这篇关于打字稿:推送不适用于自定义类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!