During my experimentation with TypeScript, I encountered an interesting behavior:
class ExtArray<U> extends Array<U> {
constructor(...args : U[]) {
super(...args);
}
public contains(element : U) : boolean {
var i = this.indexOf(element);
return i !== -1;
}
}
var test : ExtArray<string> = new ExtArray("a", "b", "c");
test.push("y");
console.log(test.length); // 1
console.log(test[0]); // y
console.log(test[1]); // undefined
console.log("Has a: " + test.contains("a")); // Has a: false
console.log("Has y: " + test.contains("y")); // Has y : true
The output of the console.log statements has been included as comments above. For an executable example and the JavaScript code, check out this TypeScript playground.
It appears that the elements passed to the constructor are not being added to the array.
The extending expression section in What's New in TypeScript suggests that extending the native Array type like this should be possible in TypeScript 1.6. However, I couldn't find any information in the TypeScript language reference that explains this behavior.
Most of the other questions I found about extending Arrays are dated at least a year old and often refer to pre-1.0 versions of TypeScript, recommending setting up the prototype chain directly.
I am puzzled by what could be going wrong here and I'm beginning to suspect a TypeScript bug or some undocumented restriction for extending Arrays.
Can anyone shed light on what might be going wrong here?