-2

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.

JW Geertsma
  • 857
  • 3
  • 13
  • 19
  • I'd go for `Array` as in my opinion it's more readable when it comes to having multiple types – Hamza Jadid Sep 07 '21 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: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#arrays. – jonrsharpe Sep 07 '21 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? – JW Geertsma Sep 07 '21 at 12:31
  • https://stackoverflow.com/q/36842158/3001761, https://stackoverflow.com/q/15860715/3001761, ... – jonrsharpe Sep 07 '21 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 is the generic syntax. They are completely equivalent. Thanks for the help! – JW Geertsma Sep 07 '21 at 12:52

1 Answers1

1

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

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ryan Le
  • 7,708
  • 1
  • 13
  • 23
  • 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. – JW Geertsma Sep 07 '21 at 12:55
  • 1
    Yeah, Use tuple when you want to create a type with a specific length with types in it. – Ryan Le Sep 07 '21 at 12:57