TypeScript:创建一个空的类型化容器数组 [英] TypeScript: Creating an empty typed container array

查看:31
本文介绍了TypeScript:创建一个空的类型化容器数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 TypeScript 创建一个简单的逻辑游戏,名为犯罪三项".

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

尝试在 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" .

也尝试这样做

var arr : Criminal = [];

这产生了无法将任何[]转换为‘犯罪’

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

执行此操作的TypeScript"方法是什么?

what is the 'TypeScript' way to do this?

推荐答案

现有答案遗漏了一个选项,所以这里是一个完整的列表:

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>();

  1. 显式指定类型是当变量声明的类型推断失败时的通用解决方案.

  1. Explicitly specifying the type is the general solution for whenever type inference fails for a variable declaration.

使用类型断言的优势(有时称为强制转换,但它在 TypeScript 中并不是真正的强制转换)适用于任何表达式,因此即使没有声明变量也可以使用它.类型断言有两种语法,但如果您关心,只有后者可以与 JSX 结合使用.

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.

使用 Array 构造函数只会在此特定用例中对您有所帮助,但我个人认为这是最易读的.但是,在运行时有轻微的性能影响*.此外,如果有人疯狂到重新定义 Array 构造函数,含义可能会改变.

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.

*:有趣的事实;在撰写本文时,Chrome 中的性能差异为 60%,而 Firefox 中没有可测量的性能差异.

*: Fun fact; at the time of writing the performance difference was 60% in Chrome, while in Firefox there was no measurable performance difference.

这篇关于TypeScript:创建一个空的类型化容器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆