【发布时间】: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