Harrison Cramer
Harrison Cramer

Reputation: 4506

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?

Upvotes: 0

Views: 48

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187272

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.

Upvotes: 2

Related Questions