0

Is there any difference between these two types?

type type1 = [String,Number][number]

type type2 = String | Number

const a: type1 = "";
const b: type1 = 1;

const c: type2 = ""
const d: type2 = 1
Mustafa Özçetin
  • 1,893
  • 1
  • 14
  • 16
Paulo Fernando
  • 3,148
  • 3
  • 5
  • 21
  • 2
    No, [they are the same](//tsplay.dev/WYlVbm). Why are you asking this? Aside from the various unconventional things happening here (user-defined types are usually written in `UpperPascalCase` not `lowercase`, so `Type1` and `Type2`; the `String` and `Number` types [are probably not the right ones to use](//www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#number-string-boolean-symbol-and-object)), why would you create a tuple and then immediately index into it this way? Without some context it seems unmotivated, like saying `let v = 3 + 5` instead of `let v = 8`. – jcalz Jul 18 '23 at 03:15
  • 2
    ... Could you [edit] to provide some clarifying context so that we can answer in terms of this context? – jcalz Jul 18 '23 at 03:16
  • I was trying to understand this [answer](https://stackoverflow.com/questions/76708464/convert-schema-to-a-type/76708668#76708668) And he used the first type, so I got curious if it would be different than a union, thanks! – Paulo Fernando Jul 18 '23 at 03:27

1 Answers1

1

No, there is no difference. If you hover over your type1, you will see that TypeScript has evaluated it and it has resolved into the union String | Number.

You can try it in the TypeScript playground

However, you shouldn't use String or Number as types in TypeScript. These refer to the String and Number constructors. Rather, you should use string and number.

See this old answer from 2013 for a more detailed explanation of the difference between String and string.

Mark Hanna
  • 3,206
  • 1
  • 17
  • 25