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
Array<Type> VS Type[] in 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[]
是数组的简写语法Type
。Array<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 ofArray<number>
, just asDate[]
is a shorthand forArray<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 readonly
type modifier. Indeed:
从 TypeScript 3.4 开始,新的类型修饰符有所不同readonly
。的确:
the
readonly
type 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 any
type 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 会变心。