简体   繁体   English

TypeScript:创建一个空类型的容器数组

[英]TypeScript: Creating an empty typed container array

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:当尝试在 TypeScript 中预分配类型化数组时,我尝试执行以下操作:

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'这产生了“无法将任何 [] 转换为 'Criminal'

what is the 'TypeScript' way to do this?执行此操作的“TypeScript”方法是什么?

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. Explicitly specifying the type is the general solution for whenever type inference fails for a variable declaration.显式指定类型是当变量声明的类型推断失败时的通用解决方案。

  2. 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.使用类型断言(有时称为强制转换,但它在 TypeScript 中并不是真正的强制转换)的优点适用于任何表达式,因此即使没有声明变量也可以使用它。 There are two syntaxes for type assertions, but only the latter will work in combination with JSX if you care about that.类型断言有两种语法,但如果您关心的话,只有后者才能与 JSX 结合使用。

  3. Using the Array constructor is something that will only help you in this specific use case, but which I personally find the most readable.使用 Array 构造函数只会在这个特定用例中为您提供帮助,但我个人认为这是最易读的。 However, there is a slight performance impact at runtime*.但是,在运行时会对性能产生轻微影响*。 Also, if someone were crazy enough to redefine the Array constructor, the meaning could change .此外,如果有人疯狂到重新定义 Array 构造函数, 其含义可能会改变

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.在撰写本文时,Chrome 中的性能差异为 60%,而 Firefox 中没有可测量的性能差异。

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.由于数组文字语法,在 TypeScript 中正确预分配类型化数组的问题有些模糊,因此它不像我最初想象的那样直观。

The correct way would be正确的方法是

var arr : Criminal[] = [];

This will give you a correctly typed, empty array stored in the variable 'arr'这将为您提供一个正确键入的空数组,该数组存储在变量“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.其中[]Criminal[]类型。

Neither return: Criminal[] [];都不return: Criminal[] []; nor return []: Criminal[];也不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.乍一看,我通过在返回之前创建一个类型化变量(如正确报告的那样)来解决它,但是(我不知道 JavaScript 引擎如何工作)它可能会产生开销并且可读性较差。

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:最终我找到了 TypeScript 类型转换,它使我能够以更简洁和可读(也许更高效)的方式解决问题:

return <Criminal[]>[];

Hope this will help future readers!希望这对未来的读者有所帮助!

对于公开访问使用如下:

public arr: Criminal[] = [];

请试试这个对我有用的。

return [] as 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 .我假设您正在使用 var ,因此这意味着在func()内的某处声明它,我的建议是使用let而不是var

If declaring it as c class property usse acces modifiers like private, public, protected.如果将其声明为 c 类属性,请使用访问修饰符,如私有、公共、受保护。

TLDR: TLDR:

// explicitly type the variable arr
var arr: Criminal[] = [];

In depth:深入:

If we have an array with no elements like:如果我们有一个没有元素的数组,例如:

var arr = [];

TS has no way of knowing at compile time what will be in that array and the type of arr will be: TS 无法在编译时知道该数组中的内容,并且arr的类型将是:

any[]

It is then the job of the programmer to tell TS the type of the array which can be done with a type annotation:然后程序员的工作就是告诉 TS 数组的类型,这可以通过类型注释来完成:

var arr: Criminal[] = [];

If we then were to get an element out of the array Typescript knows the element will be of type Criminal .如果我们然后从数组 Typescript 中获取一个元素,则知道该元素将是类型Criminal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM