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.
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.
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.
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) => {
//..
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With