Typescript联合类型和”索引元组”之间的区别 🤷

huangapple go评论168阅读模式
英文:

Typescript difference between union types and "indexed tuple" 🤷

问题

这两种类型之间有什么区别?

  1. type type1 = [String, Number][number];
  2. type type2 = String | Number;
  3. const a: type1 = "";
  4. const b: type1 = 1;
  5. const c: type2 = "";
  6. const d: type2 = 1;
英文:

Is there any difference between these two types?

  1. type type1 = [String,Number][number]
  2. type type2 = String | Number
  3. const a: type1 = "";
  4. const b: type1 = 1;
  5. const c: type2 = ""
  6. const d: type2 = 1

答案1

得分: 1

不,没有区别。如果你悬停在你的 type1 上,你会看到 TypeScript 已经对它进行了评估,它已经解析成了联合类型 string | number

你可以在 TypeScript playground 中尝试。

然而,在 TypeScript 中,你不应该使用 StringNumber 作为类型。这些是指 StringNumber 构造函数。相反,你应该使用 stringnumber

参见这个来自2013年的旧答案以获得关于 Stringstring 之间区别的更详细解释。

英文:

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.

huangapple
  • 本文由 发表于 2023年7月18日 11:10:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定