TypeScript casting arrays

CastingTypescript

Casting Problem Overview


I'm trying to use a wrapper for a library that wants an Array as an input parameter.

I tried casting the Array, but I get an error: Cannot convert 'any[]' to 'Array'

Is there a way to make this work?

var rows = new Array(10);
var rows2 = <Array>rows; //<--- Cannot convert 'any[]' to 'Array'

Casting Solutions


Solution 1 - Casting

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.

Solution 2 - Casting

I think the right syntax is:

var rows2 = <Array<any>>rows;

That's how you cast to interface Array<T>

Solution 3 - Casting

I think this is just a bug - can you log an issue on the CodePlex site?

As a workaround, you can write <Array><any>rows;

Solution 4 - Casting

A simple solution for all types

const myArray = <MyType[]>value;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdam TegenView Question on Stackoverflow
Solution 1 - CastingshadeglareView Answer on Stackoverflow
Solution 2 - CastingTsvetomir NikolovView Answer on Stackoverflow
Solution 3 - CastingRyan CavanaughView Answer on Stackoverflow
Solution 4 - CastingJayant VarshneyView Answer on Stackoverflow