数组<类型>VS Type[] 在打字稿中 [英] Array<Type> VS Type[] in Typescript
问题描述
据我所知,当它是一个数组时,可以通过两种方式定义一个属性的类型.
As far as I know a property's type can be defined in two ways when it's an Array.
property_name: type
类型可以是其中之一
Array<string>, Array<MyType>, etc. (e.g. let prop1: Array<string>)
和
string[], MyType[], etc. (e.g. let prop1: string[])
这两种情况之间的区别是什么?或者我误解了什么(也许是关于 <> 在铸造中使用的?)
What is the difference between the two cases? Or am I misunderstanding something (perhaps something about <> used in casting?)
EDIT 由于问题被标记为重复,我知道还有一个关于 any[] 的问题,但在发布之前我仍然看过它,对我来说更多的是关于类型'any' 比不同的 [] VS <> 我问
EDIT since 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
推荐答案
没有任何语义差异
完全没有区别.Type[]
是 Type
数组的速记语法.Array
是通用语法.它们完全等效.
There isn't any semantic difference
There is no difference at all. Type[]
is the shorthand syntax for an array of Type
. Array<Type>
is the generic syntax. They are completely equivalent.
手册提供了此处的示例一>.相当于写:
The handbook provides an example here. It is equivalent to write:
function loggingIdentity<T>(arg: T[]): T[] {
console.log(arg.length);
return arg;
}
或者:
function loggingIdentity<T>(arg: Array<T>): Array<T> {
console.log(arg.length);
return arg;
}
这里引用了 一些发行说明:
具体来说,number[]
是 Array
的简写版本,就像 Date[]
是 的简写一样>数组<日期>
.
Specifically,
number[]
is a shorthand version ofArray<number>
, just asDate[]
is a shorthand forArray<Date>
.
关于readonly
类型修饰符
TypeScript 3.4,引入了 readonly
类型修饰符.使用 精确:
About the readonly
type modifier
TypeScript 3.4, introduces the readonly
type modifier. With a precision:
readonly
类型修饰符只能用于数组类型和元组类型的语法
the
readonly
type modifier can only be used for syntax on array types and tuple types
let err2: readonly Array<boolean>; // error!
let okay: readonly boolean[]; // works fine
以下声明等价于readonly boolean[]
:
let okay2: ReadonlyArray<boolean>;
这篇关于数组<类型>VS Type[] 在打字稿中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!