英文:
Typescript difference between union types and "indexed tuple" 🤷
问题
这两种类型之间有什么区别?
type type1 = [String, Number][number];
type type2 = String | Number;
const a: type1 = "";
const b: type1 = 1;
const c: type2 = "";
const d: type2 = 1;
英文:
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
答案1
得分: 1
不,没有区别。如果你悬停在你的 type1
上,你会看到 TypeScript 已经对它进行了评估,它已经解析成了联合类型 string | number
。
你可以在 TypeScript playground 中尝试。
然而,在 TypeScript 中,你不应该使用 String
或 Number
作为类型。这些是指 String
和 Number
构造函数。相反,你应该使用 string
和 number
。
参见这个来自2013年的旧答案以获得关于 String
和 string
之间区别的更详细解释。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论