Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript casting arrays

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' 
like image 702
Adam Tegen Avatar asked Oct 09 '12 04:10

Adam Tegen


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 *.

Can you cast in TypeScript?

Surprisingly, the typescript programming language, which compiles to JavaScript, has the idea of casting. Since the variables in JavaScript have dynamic types, there is no concept of type casting in Javascript. TypeScript, on the other hand, assigns a type to every variable.

How do I cast objects in TypeScript?

If we want to cast the object to string data types by using toString() method we can change the object type to a string data type. We can also cast the object type to jsonby using json. parse() method we can get only the plain objects and it not used on the class object.


2 Answers

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.

like image 153
shadeglare Avatar answered Sep 28 '22 06:09

shadeglare


I think the right syntax is:

var rows2 = <Array<any>>rows; 

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

like image 29
Tsvetomir Nikolov Avatar answered Sep 28 '22 06:09

Tsvetomir Nikolov