简体   繁体   中英

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:

type stringArray = string[]

I'm able to specify that certain kinds of objects may go into an array like this:

type myObject  = { 
    one: string,
    two: string,
}
type objectArray = myObject[]

However, I'm able to accomplish something very similar with generics, like this:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM