Array-destructuring of array-like objects when targeting ES5
Continuing from #3252
Currently, array-destructuring of array-like objects is invalid in Typescript targeting ES5 because of how slice() is used in order to implement spread operators (and maybe some other things that I'm not aware of). If the problem is just the slice() call, this could be a solution that enables this feature while targeting ES5:
// typescript
var arrayLike = {
'0': 'foo',
'1': 'bar',
'2': 'baz'
};
var [foo, ...bar] = arrayLike;
console.log(foo, bar); // 'foo', ['bar', 'baz']
// output
var arrayLike = {
'0': 'foo',
'1': 'bar',
'2': 'baz'
};
var foo = arrayLike[0], bar = arrayLike.slice(1); // error
// desired output
var arrayLike = {
'0': 'foo',
'1': 'bar',
'2': 'baz'
};
var foo = arrayLike[0], bar = Array.prototype.slice.call(arrayLike, 1);
console.log(foo, bar); // 'foo', ['bar', 'baz']
This is by design. spread is only supported on arrays, and not arraylike; this code generates an error:
error TS2461: Type '{ '0': string; '1': string; '2': string; }' is not an array type.
I should add that the reason is we have avoided type-directed emit; so all code should emit the same way regardless of types (a similar case is how for..of is emitted in ES5); also we have avoided relying on helper functions that may affect your code performance.
@tylergoodman I think you have to say "array-like with an iterator", as even ES6 spec does not support destructuring non-iterable object.
one thing to note, iterables are only supported when using --target ES6
i'm not sure but allowing symbols only on interfaces may enable some codes with array-likes:
interface NodeListOf<TNode extends Node> {
[Symbol.iterator](): IterableIterator<TNode> // Not error
}
for (let node of document.getElementsByTagName('p')) {
// Not error. Currently impossible in ES5 mode
}
Symbol.iterator // Error
NodeList.prototype[Symbol.iterator] // Error
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>
}
let nodeList: Iterable<string> = ["foo"];
// Incompatibility error
nodeList = { '0': 'this', '1': 'still will not', '2': 'enable this scenario' };