97

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'
1
  • I can convert the wrapper to any[], but I'd like to know why I can't cast to an Array. Commented Oct 9, 2012 at 4:13

4 Answers 4

148

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.

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

Comments

17

I think the right syntax is:

var rows2 = <Array<any>>rows;

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

Comments

5

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;

1 Comment

Presumably the issue has been fixed. And I think you all are using GitHub now? ;)
5

A simple solution for all types

const myArray = <MyType[]>value;

1 Comment

this do not work, if you console log the result , myArray is not a array of MyType elements

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.