Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast to array in TypeScript 2?

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.

like image 503
FlavorScape Avatar asked Sep 22 '16 22:09

FlavorScape


People also ask

How do I cast an array in TypeScript?

There are 4 possible conversion methods in TypeScript for arrays: let x = []; //any[] let y1 = x as number[]; let z1 = x as Array<number>; let y2 = <number[]>x; let z2 = <Array<number>>x; The as operator's mostly designed for *. tsx files to avoid the syntax ambiguity.

Can you type cast in TypeScript?

Converting a variable from one type to another is possible with type casting in Typescript. Type casting in TypeScript can be done with the 'as' keyword or the '<>' operator.


3 Answers

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.

like image 182
Nitzan Tomer Avatar answered Nov 05 '22 23:11

Nitzan Tomer


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[].

like image 24
chrisbajorin Avatar answered Nov 06 '22 00:11

chrisbajorin


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

var n = (<SampleType[]>result.data['value']).map((a) => {
    //..
});
like image 1
Gorka Hernandez Avatar answered Nov 06 '22 00:11

Gorka Hernandez