How to cast to array in TypeScript 2? How to cast to array in TypeScript 2? typescript typescript

How to cast to array in TypeScript 2?


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.


You're not casting to an array.

[string] is a tuple with a single element string.

[string, string] is a tuple with two elements, string and string.

[] is a tuple with zero elements.

The syntax for an array of strings is string[]

What you likely want is result.data['value'] as any[].


Alternatively to the previous cast syntax options mentioned above, you can also do the following:

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