[英]Using Generics in Typescript with Arrays
In Typescript, if I'm defining a type that stipulates only strings can go into an array, I'm able to define that like this:在 Typescript 中,如果我定义的类型规定只有字符串可以将 go 放入数组中,我可以这样定义:
type stringArray = string[]
I'm able to specify that certain kinds of objects may go into an array like this:我可以指定某些类型的对象可能 go 进入这样的数组:
type myObject = {
one: string,
two: string,
}
type objectArray = myObject[]
However, I'm able to accomplish something very similar with generics, like this:但是,我能够完成与 generics 非常相似的事情,如下所示:
type stringArray = Array<string>
and和
type objectArray = Array<myObject>
Is there any advantage to using either approach?使用这两种方法有什么好处吗? When should one use the former and when is the latter a better approach?
什么时候应该使用前者,什么时候使用后者更好?
Array<T>
and T[]
are 100% equivalent. Array<T>
和T[]
100% 等效。
Which to use is mostly a code style choice.使用哪个主要是代码风格的选择。 Though the
T[]
syntax is usually preferred in most codebases that I've seen as it looks like an array, and at a glance it is shorter.尽管在我见过的大多数代码库中通常首选
T[]
语法,因为它看起来像一个数组,而且乍一看它更短。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.