Typescript 中的 Array<Type> VS Type[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36842158/
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-09-09 07:05:51  来源:igfitidea点击:

Array<Type> VS Type[] in Typescript

typescript

提问by dragonmnl

As far as I know a property's type can be defined in two ways when it's an Array.

据我所知,当它是一个数组时,可以通过两种方式定义属性的类型。

property_name: type

where type can be either

其中类型可以是

Array<string>, Array<MyType>, etc. (e.g. let prop1: Array<string>)

and

string[], MyType[], etc. (e.g. let prop1: string[])

What is the differencebetween the two cases? Or am I misunderstanding something (perhaps something about <> used in casting?)

这两种情况有什么区别?或者我误解了什么(也许是关于铸造中使用的 <> ?)

EDITsince the question is marked as duplicate, I am aware there is the other question about any[] but still I had a look at it before posting and to me it was more about the type 'any' than the different [] VS <> I asked

编辑,因为问题被标记为重复,我知道还有关于 any[] 的另一个问题,但在发布之前我仍然看过它,对我来说它更多的是关于类型“any”而不是不同的 [] VS < > 我问

回答by Paleo

There isn't any semantic difference

没有任何语义差异

There is no difference at all. Type[]is the shorthand syntaxfor an array of Type. Array<Type>is the generic syntax. They are completely equivalent.

完全没有区别。Type[]是数组的简写语法TypeArray<Type>通用语法。它们是完全等效的。

The handbook provides an example here. It is equivalent to write:

手册在这里提供了一个示例。相当于写:

function loggingIdentity<T>(arg: T[]): T[] {
    console.log(arg.length);
    return arg;
}

Or:

或者:

function loggingIdentity<T>(arg: Array<T>): Array<T> {
    console.log(arg.length);
    return arg;
}

And here is a quote from some release notes:

这是一些发行说明中的引用:

Specifically, number[]is a shorthand version of Array<number>, just as Date[]is a shorthand for Array<Date>.

具体而言,number[]是的简写版Array<number>,就像Date[]是一个速记Array<Date>

However, there is a case where the shorthand syntax is required

但是,有一种情况需要速记语法

Since TypeScript 3.4, there is a differencefor the new readonlytype modifier. Indeed:

从 TypeScript 3.4 开始,新的类型修饰符有所不同readonly。的确:

the readonlytype modifier can only be used for syntax on array types and tuple types

readonly类型修饰符只能用于语法上数组类型和的元组类型

let err1: readonly Set<number>; // error!
let err2: readonly Array<boolean>; // error!

let okay: readonly boolean[]; // works fine

回答by Ozrix

foo: Array

means that it's a plain array, with an implicit anytype for it's members

意味着它是一个普通数组,any其成员具有隐式类型

foo: string[]

means that it's an array of strings, i.e. TypeScript will go mental if you try pushing anything other than strings into that array.

意味着它是一个字符串数组,也就是说,如果您尝试将字符串以外的任何内容推送到该数组中,TypeScript 会变心。