i want create a array-like class
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}
But How can i defined like this in Typescript
Can't access them in ts
typescript error:
Property '0' does not exist on type 'Demo'. (2339)
You can extend the Array
object:
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.