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?
This question is related to
javascript
arrays
typescript
Please try this which it works for me.
return [] as Criminal[];
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!
I know this is an old question but I recently faced a similar issue which couldn't be solved by this way, as I had to return an empty array of a specific type.
I had
return [];
where []
was Criminal[]
type.
Neither return: Criminal[] [];
nor return []: Criminal[];
worked for me.
At first glance I solved it by creating a typed variable (as you correctly reported) just before returning it, but (I don't know how JavaScript engines work) it may create overhead and it's less readable.
For thoroughness I'll report this solution in my answer too:
let temp: Criminal[] = [];
return temp;
Eventually I found TypeScript type casting, which allowed me to solve the problem in a more concise and readable (and maybe efficient) way:
return <Criminal[]>[];
Hope this will help future readers!
For publicly access use like below:
public arr: Criminal[] = [];
Okay you got the syntax wrong here, correct way to do this is:
var arr: Criminal[] = [];
I'm assuming you are using var so that means declaring it somewhere inside the func()
,my suggestion would be use let
instead of var
.
If declaring it as c class property usse acces modifiers like private, public, protected.
Source: Stackoverflow.com