【问题标题】:Typescript: push not available on custom typed array打字稿:推送在自定义类型数组上不可用
【发布时间】:2015-03-23 10:16:14
【问题描述】:

使用 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 数组。我说的不对吗?

【问题讨论】:

  • 看看你的接口定义——你定义的是一个类似数组的对象,而不是一个实际的数组。

标签: javascript arrays typescript


【解决方案1】:

你快到了。您确实将其定义为带有索引器的对象。不是数组,见下例

possibleAnswers : {
        id : number;
        vocab : string;
        comment : string;
}[];

【讨论】:

猜你喜欢
  • 2019-07-12
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2017-04-13
  • 2017-02-20
相关资源
最近更新 更多