-1

What would be the best or most common way to declare an array type in TypeScript? There are several ways to do it but I'm not sure if it matters how you do it.

This is how I created the array type initially:

export type LayoutSpacingType = [number | SpacingInterface];

A colleague mentioned that it could also be done like this:

export type LayoutSpacingType = (number | SpacingInterface)[];

The difference is that one approach is wrapping the square brackets around both of the types, and the other one is just adding the square brackets at the end.

We are in doubt which one we should use. Are there any advantages or disadvantages for those approaches? Or will this basically compile to the same code and is the notation something that you could prefer on a personal level?

I did some research but couldn't find anything specific about the advantages / disadvantages. We want to make sure that we pick the best way to do it.

5
  • I'd go for Array<number | SpacingInterface> as in my opinion it's more readable when it comes to having multiple types Commented Sep 7, 2021 at 12:22
  • 3
    The first one is not an array type, it's a tuple (containing only a single element). There are two options for defining an array type, though, and they're listed in the docs: typescriptlang.org/docs/handbook/2/everyday-types.html#arrays. Commented Sep 7, 2021 at 12:23
  • Right! That makes sense @jonrsharpe. We didn't know about the tuple type. I do have a follow-up question though. Is there any important difference in those two ways to declare an array? Or is it just a matter of personal taste/preference? Commented Sep 7, 2021 at 12:31
  • stackoverflow.com/q/36842158/3001761, stackoverflow.com/q/15860715/3001761, ... Commented Sep 7, 2021 at 12:34
  • I dived a bit more into it and it seems that there is no difference at all. I found out that Type[] is the shorthand syntax for an array of Type. Array<Type> is the generic syntax. They are completely equivalent. Thanks for the help! Commented Sep 7, 2021 at 12:52

1 Answer 1

3

They are two different types in TypeScript: tuple & array.

export type LayoutSpacingType = [number | string];

const var1: LayoutSpacingType = [2, 3];   // <-- NOT VALID, ALLOW ONLY "ONE" ITEM

export type ArrayType = (number | string)[];

const var2: ArrayType = [2, 3];  // <-- VALID, ALLOW MANY ITEMS

Playground Link

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for the help! I didn't know about the tuple type. It all makes sense now! We will use the ArrayType[] shorthand syntax in our code to declare an array.
Yeah, Use tuple when you want to create a type with a specific length with types in it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.