Here’s a complete list of options for initializing a typed array in TypeScript:
Explicitly declare the type:
var arr: Criminal[] = [];
Via type assertion:
Via type assertion:
var arr = <Criminal[]>[];
var arr = [] as Criminal[];
Using the Array constructor:
var arr = new Array<Criminal>();
Explicitly specifying the type is a solid, general approach when type inference doesn’t quite get you what you need. It’s clear and straightforward, but sometimes might feel a bit verbose.
Type assertions (sometimes called “casts,” though they’re not true casts in TypeScript) give you flexibility. They can be applied to any expression, even without declaring a variable. The two assertion syntaxes are interchangeable, except if you’re working with JSX, in which case you’ll want to use the as
syntax.
Now, I personally favor using the Array constructor. It feels cleaner to me, and the syntax is a bit more compact. That said, there’s a minor runtime performance hit to be aware of, and, in rare cases, if someone redefines the Array
constructor, you might get unexpected behavior. But honestly, in most scenarios, the impact is minimal, and I think the added readability makes it worth it.
Fun fact: When I last checked, the performance difference was about 60% in Chrome, while Firefox didn’t show any measurable difference. But unless you’re dealing with performance-critical code, the readability and clarity usually take priority!