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

Sha*_*ngh 4 typescript angular

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

mar*_*ter 9

使用管道符号分隔|的类型称为union-types,可以作为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";
Run Code Online (Sandbox Code Playgroud)

要了解有关TypeScript中高级类型的更多信息,我强烈推荐有关高级类型文档