【问题标题】:angular2 and Typescript array - Property 'push' does not exist on type '() => void'angular2 和 Typescript 数组 - 类型 '() => void' 上不存在属性 'push'
【发布时间】:2016-08-08 15:04:35
【问题描述】:

如何初始化一个空数组?

test: any[];

//On change I want to add an item to an array
test(){ 
  this.test.push('a');
}

错误 TS2339:类型 '() => void' 上不存在属性 'push'。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    你没有初始化你的数组,所以test 是undefined。为了能够使用它,只需这样初始化它:

    test: any[] = [];
    

    【讨论】:

    • 我遇到了与 IntelliJ 警告相同的问题,但这可能只是 IntellIJ 错误。 TypeScript 编译器不会抱怨它。
    • 我想评论 Thierry 的回复,但缺乏声誉。您必须在 IDE 中使用与 Angular 配置中的版本相同的 typescript 版本,以避免看到任何语法错误和代码完成建议。
    【解决方案2】:

    尝试以下任一解决方案:

    const test = [];
    test.push('a');
    

    或

    const test = [];
    const name = 'a';
    test.push({ 'name' : name});
    

    您可以将其添加到您的函数中,例如:

    test(name: string){
        const test = [];
        test.push({ 'name' : name});
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-21
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2019-12-31
      • 1970-01-01
      • 2016-12-31
      相关资源
      最近更新 更多