public testOptions: "Undecided" | "Yes" | "No" = "Undecided";
答案 0 :(得分:9)
使用管道符号|
分隔的类型称为联合类型,可以作为OR
操作读取。此案例中的=
符号表示作业。含义属性testOptions
具有默认值"Undecided"
您的代码可以重写为:
// Foo is of type string, but not just any string, only the literal values
// "Undecided", "Yes", or "No". Any other string won't match the type.
type Foo = "Undecided" | "Yes" | "No";
// Will error because "bar" is not one of "Undecided", "Yes", or "No"
const a: Foo = "bar";
// Will work
const b: Foo = "Undecided";
要详细了解TypeScript中的高级类型,我强烈推荐docs on advanced types
答案 1 :(得分:3)
在打字稿中,变量类型定义为variableName: type
。
类型可以是任何东西。
还有一个联合运算符(|
),用于合并多种类型。
因此,如果您有一个可以包含数字或字符串的变量,那么它将被定义为variable: number | string
。
现在如果你想拥有一个只能在特定类型中拥有特定值的变量呢?
public testOptions:" Undecided" | "是" | "否" ="未定&#34 ;;
现在,您的testOptions
可以"Undecided" | "Yes" | "No"
,您可以将其默认设置为"Undecided"
答案 2 :(得分:1)
public testOptions: "Undecided" | "Yes" | "No" = "Undecided";
"Undecided" | "Yes" | "No"
如果更改值
public testOptions: "Undecided" | "Yes" | "No" = "decided";
它会抛出错误,因为它是字符串但它应该超出"Undecided" | "Yes" | "No"
这段代码创建了一个新类型,就像string,objject,number;此代码创建了一个用户定义的类型
type UndecideYesNoType = "Undecided" | "Yes" | "No";
答案 3 :(得分:1)
它就像一个缺少enum
......
以下将编译:
testOptions: "Undecided" | "Yes" | "No" = "Undecided";
testOptions: "Undecided" | "Yes" | "No" = "Yes";
testOptions: "Undecided" | "Yes" | "No" = "No";
testOptions: "a" | "b" | "c" = "a";
这不会编译:
testOptions: "Undecided" | "Yes" | "No" = "xxx";
testOptions: "a" | "b" | "c" = "xxx";
因为" xxx"在高级类型声明中不存在。
与枚举相反:
enum MyEnum{
Undecided= 1,
Yes,
No
}
testOptions:MyEnum = MyEnum.Yes; <-- so much easier to understand