TypeScript: Creating an empty typed container array

darethas picture darethas · Apr 5, 2013 · Viewed 195.9k times · Source

I am creating simple logic game called "Three of a Crime" in TypeScript.

When trying to pre-allocated typed array in TypeScript, I tried to do something like this:

var arr = Criminal[];

which gave the error "Check format of expression term" .

also tried doing this

var arr : Criminal = [];

and this produced "cannot convert any[] to 'Criminal'

what is the 'TypeScript' way to do this?

Answer

darethas picture darethas · Apr 5, 2013

The issue of correctly pre-allocating a typed array in TypeScript was somewhat obscured for due to the array literal syntax, so it wasn't as intuitive as I first thought.

The correct way would be

var arr : Criminal[] = [];

This will give you a correctly typed, empty array stored in the variable 'arr'

Hope this helps others!