Skip to content

Instantly share code, notes, and snippets.

@nabeix
Last active October 2, 2019 12:12
Show Gist options
  • Save nabeix/313566abd96e17997f8853e49ba103bc to your computer and use it in GitHub Desktop.
Save nabeix/313566abd96e17997f8853e49ba103bc to your computer and use it in GitHub Desktop.
typescript-extends-builtin-array
// BAD
class A extends Array {
constructor(array: number[]) {
super();
console.log(array); // called twice with other array 1st => [1, 2, 3], 2nd(not an array type) => 3
array.forEach((a, i) => this[i] = a); // => Uncaught TypeError: array.forEach is not a function
}
}
const a = new A([1,2,3]);
a.map(b => {
console.log(b);
})
// OK
class A extends Array {
static fromArray(arr: number[]): A {
const c = new A();
arr.forEach((a, i) => c[i] = a);
return c;
}
}
const a = A.fromArray([1,2,3]);
a.map(b => {
console.log(b);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment