Issue
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?
Solution
The existing answers missed an option, so here's a complete list:
// 1. Explicitly declare the type
var arr: Criminal[] = [];
// 2. Via type assertion
var arr = <Criminal[]>[];
var arr = [] as Criminal[];
// 3. Using the Array constructor
var arr = new Array<Criminal>();
Explicitly specifying the type is the general solution for whenever type inference fails for a variable declaration.
The advantage of using a type assertion (sometimes called a cast, but it's not really a cast in TypeScript) works for any expression, so it can be used even when no variable is declared. There are two syntaxes for type assertions, but only the latter will work in combination with JSX if you care about that.
Using the Array constructor is something that will only help you in this specific use case, but which I personally find the most readable. However, there is a slight performance impact at runtime*. Also, if someone were crazy enough to redefine the Array constructor, the meaning could change.
It's a matter of personal preference, but I find the third option the most readable. In the vast majority of cases the mentioned downsides would be negligible and readability is the most important factor.
*: Fun fact; at the time of writing the performance difference was 60% in Chrome, while in Firefox there was no measurable performance difference.
Answered By - Thorarin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.