打字稿中这段代码的含义是什么? public testOptions:“未定”| “是的”| “不”=“未定”;

时间:2018-02-08 07:15:16

标签: angular typescript

public testOptions: "Undecided" | "Yes" | "No" = "Undecided";
  1. 这段代码的含义是什么意思?
  2. 什么是变量testOptions的类型?
  3. testOptions是数组,字符串还是其他东西?
  4. “不”=“未定”是什么意思?
  5. 管道符号“|”是什么意思?

4 个答案:

答案 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

类型可以是任何东西。

  • 原始值:字符串,数字
  • 复杂值:MyClass1,IInterface1

还有一个联合运算符(|),用于合并多种类型。

因此,如果您有一个可以包含数字或字符串的变量,那么它将被定义为variable: number | string

现在如果你想拥有一个只能在特定类型中拥有特定值的变量呢?

  

public testOptions:" Undecided" | "是" | "否" ="未定&#34 ;;

现在,您的testOptions可以"Undecided" | "Yes" | "No",您可以将其默认设置为"Undecided"

答案 2 :(得分:1)

public testOptions: "Undecided" | "Yes" | "No" = "Undecided";
  1. 您已定义了一个字符串变量。
  2. 字符串,但是"Undecided" | "Yes" | "No"
  3. 之一

    如果更改值

    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