在 TypeScript 0.9.0.1 中创建类型化数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17683153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:50:22  来源:igfitidea点击:

Creating typed array in TypeScript 0.9.0.1

typescript

提问by dpoiu

How to create a typed array in TypeScript 0.9.0.1? In 0.8.x.x, I created a typed array like this:

如何在中创建类型化数组TypeScript 0.9.0.1?在 中0.8.x.x,我创建了一个这样的类型化数组:

public myArray: myClass[] = new myClass[];

But in TypeScript 0.9.0.1, I get this error:

但是在 中TypeScript 0.9.0.1,我收到此错误:

error TS2068: 'new T[]' cannot be used to create an array. Use 'new Array<T>() instead.

And if I try the following way:

如果我尝试以下方式:

public myArray: myClass[] = new myClass<myClass>();

I get another error. So, what's the correct way to create a typed array in TypeScript?

我收到另一个错误。那么,在 TypeScript 中创建类型化数组的正确方法是什么?

回答by nikeee

Since TypeScript 0.9 you can use generics and do it like this:

从 TypeScript 0.9 开始,您可以使用泛型并这样做:

var myArray = new Array<MyClass>();

Or like this (TS 0.9 and below):

或者像这样(TS 0.9 及以下):

var myArray: MyClass[] = [];

And this should also work (using cast operation):

这也应该有效(使用强制转换操作):

var myArray = <MyClass[]>[];

I personally like the second and the first way.

我个人喜欢第二种和第一种方式。

回答by Fenton

You do it like this... Only the type annotation needs the type:

你这样做......只有类型注释需要类型:

var myArray: MyClass[] = [];

This tricks almost everyone at first - so your question is a good one.

一开始这几乎欺骗了每个人 - 所以你的问题是个好问题。