How to cast to array in TypeScript 2?

37,048

Solution 1

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.

Solution 2

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

Solution 3

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

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

Related videos on Youtube

FlavorScape
Author by

FlavorScape

Listen to the album, Bitwize Operata Now! Music Videos: Decompiled A song about the development industry Rigid Body Physics learn how to make a rigid body physics engine I make drawings. Lots of drawings. See them here: ForeverScape.com Gihub: https://github.com/ForeverScape

Updated on January 10, 2020

Comments

  • FlavorScape
    FlavorScape over 4 years

    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.

    • FlavorScape
      FlavorScape almost 8 years
      I mean, I could cast it to my final type [IWhatever] but I don't feel that's necessary here, I just want to use the array methods.

Related