18

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.

3
  • What's the type of result.data['value']? Commented Sep 22, 2016 at 22:53
  • it's just a simple array. Commented Sep 22, 2016 at 22:57
  • 1
    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. Commented Sep 22, 2016 at 22:58

3 Answers 3

35

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.