![](/img/trans.png)
[英]how to insert a property in typescript class which is not defined in the interface
[英]How to defined dynamic property in typescript
我想創建一個類似數組的類
class Demo {
constructor() {
[1, 2, 3, 4, 5].forEach((v, i)=> this[i] = v);
}
}
let demo = new Demo();
console.log(demo); // Demo {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
但是我該如何在Typescript中定義
在ts中無法訪問它們
typescript error:
Property '0' does not exist on type 'Demo'. (2339)
您可以擴展Array
對象:
class Demo extends Array<number> {
constructor() {
super();
[1, 2, 3, 4, 5].forEach(v => this.push(v))
}
}
let a = new Demo();
console.log(a[0]); // 1
a.forEach(item => console.log(item));
( 操場上的代碼 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.