How to cast to array in TypeScript 2?

FlavorScape picture FlavorScape · Sep 23, 2016 · Viewed 31.1k times · Source

I had some code that cast an object to type array (so I could use array functions on the object without compile errors).

    var n = (result.data['value'] as []).map( (a)=>{
      //..
    });

But on upgrade to ts2, I get:

error TS1122: A tuple type element list cannot be empty.

Which is actually a syntax error, claiming you forgot a comma or value. So, how do I modify this cast to work correctly?

I tried as [IMyType] and it worked, but I'd prefer not to specify type since I only need the array.prototype functions here... also, I don't think that's how you actually do it.

Answer

Nitzan Tomer picture Nitzan Tomer · Sep 23, 2016

For some reason the compiler thinks that result.data['value'] is a tuple and not an array.

You can cast it like this:

result.data['value'] as any[]

Which should tell the compiler that it's an array, or:

result.data['value'] as Array<any>

If your array has only items of type IMyType then simply:

result.data['value'] as IMyType[]

However, if your array contains items of different types then it's either a any[] or a tuple, for example:

result.data['value'] as [IMyType, string, string]

In any case, in the compiled js it will be an array, but tuples let you define a fixed length arrays with specific types.