Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating typed array in TypeScript 0.9.0.1

Tags:

typescript

How to create a typed array in TypeScript 0.9.0.1? In 0.8.x.x, I created a typed array like this:

public myArray: myClass[] = new myClass[];

But in TypeScript 0.9.0.1, I get this error:

error TS2068: 'new T[]' cannot be used to create an array. Use 'new Array<T>() instead.

And if I try the following way:

public myArray: myClass[] = new myClass<myClass>();

I get another error. So, what's the correct way to create a typed array in TypeScript?

like image 423
dpoiu Avatar asked Jul 16 '13 17:07

dpoiu


1 Answers

Since TypeScript 0.9 you can use generics and do it like this:

var myArray = new Array<MyClass>();

Or like this (TS 0.9 and below):

var myArray: MyClass[] = [];

And this should also work (using cast operation):

var myArray = <MyClass[]>[];

I personally like the second and the first way.

like image 111
nikeee Avatar answered Oct 03 '22 21:10

nikeee