【问题标题】:Why is Array concatenation throwing an error in TypeScript?为什么数组连接会在 TypeScript 中引发错误?
【发布时间】:2021-07-30 17:30:47
【问题描述】:

我对 TypeScript 很陌生。我正在试验类,碰巧看到一个错误。

class DataStorage {
    private data:string[] = [];
    
    addItem(item: string){
        this.data.push(item);
    }

    removeItem(item: string){
        this.data.splice(this.data.indexOf(item), 1);
    }

    getItems(): string[]{
        return [...this.data];
    }

    // below code gives an error
    getConcatedItems(){
        const arr:string[] = [];
        return arr.concat[this.data];
    }
}

在上面的代码中,getConcatedItems 中的 this.data 显示了一个错误,即 Type 'string[]' cannot be used as an index type.。而getItems 没有显示任何错误。

为什么会发生这种情况?有什么办法可以解决这个问题?

【问题讨论】:

  • 因为需要arr.concat(this.data);
  • 你使用方括号调用函数

标签: arrays string typescript concatenation


【解决方案1】:

只是拼写错误。应该是

return arr.concat(this.data);

所以圆括号而不是方括号。

【讨论】:

    猜你喜欢
    • 2023-02-18
    • 1970-01-01
    • 2018-03-30
    • 2021-04-21
    • 1970-01-01
    • 2011-11-08
    • 2021-12-07
    • 1970-01-01
    • 2020-12-09
    相关资源
    最近更新 更多