TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Array-destructuring of array-like objects when targeting ES5

Open tylergoodman opened this issue 11 years ago • 5 comments

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']

tylergoodman avatar Jun 04 '15 20:06 tylergoodman

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.

mhegazy avatar Jun 04 '15 21:06 mhegazy

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.

mhegazy avatar Jun 04 '15 21:06 mhegazy

@tylergoodman I think you have to say "array-like with an iterator", as even ES6 spec does not support destructuring non-iterable object.

saschanaz avatar Jun 05 '15 03:06 saschanaz

one thing to note, iterables are only supported when using --target ES6

mhegazy avatar Jun 05 '15 22:06 mhegazy

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' };

saschanaz avatar Jun 06 '15 12:06 saschanaz