TypeScript日常类型(10): Less Common Primitives

71 阅读3分钟

不太常见的原始类型

值得一提的是 JavaScript 中其余的原始类型,它们在类型系统中也有所表示。尽管我们不会在这里深入讨论这些类型。

bigint

从 ES2020 开始,JavaScript 引入了一种用于表示非常大的整数的原始类型 BigInt:


// 使用 BigInt 函数创建 bigint
const oneHundred: bigint = BigInt(100);

// 使用字面量语法创建 BigInt
const anotherHundred: bigint = 100n;

你可以在 TypeScript 3.2 的发布说明中了解更多关于 BigInt 的内容。

symbol

JavaScript 中有一个原始类型,用于通过 Symbol() 函数创建全局唯一的引用:

const firstName = Symbol("name");
const secondName = Symbol("name");

const comparison = firstName === secondName 
// ❌ This comparison appears to be unintentional because the types 'typeof firstName' and 'typeof secondName' have no overlap.

null 和 undefined

JavaScript 有两个原始值用于表示缺失或未初始化的值:null 和 undefined。

TypeScript 也有两个对应的类型,分别是 null 和 undefined。这些类型的行为取决于你是否启用了 strictNullChecks 选项。

strictNullChecks 关闭时的行为

当 strictNullChecks 选项关闭时,可能是 null 或 undefined 的值仍然可以正常访问,并且 null 和 undefined 可以被赋值给任何类型的属性。这类似于没有空值检查的编程语言(例如 C# 或 Java)的行为。

function doSomething(x: string | null) {
  if (x === null) {
    let str: string = x
    console.log(str)
  } else {
    console.log("Hello, " + x.toUpperCase());
  }
}

strictNullChecks 开启时的行为

当 strictNullChecks 选项开启时,TypeScript 会要求你在使用 null 或 undefined 的值之前进行检查。你必须确保在访问该值的方法或属性之前,已验证它不是 null 或 undefined。这可以通过 类型保护(Type Guards)来实现。

function doSomething(x: string | null) {
  if (x === null) {
    let str: string = x // ❌ Type 'null' is not assignable to type 'string'.
    console.log(str)
  } else {
    // 如果 x 不是 null,那么它一定是一个 string 类型
    console.log("Hello, " + x.toUpperCase());
  }
}

非空断言操作符(Postfix !)

TypeScript 提供了一种特殊的语法,可以在不做显式检查的情况下将 null 和 undefined 从类型中移除。通过在任何表达式后面写 !,实际上是在进行类型断言,告诉 TypeScript 该值不是 null 或 undefined。

function liveDangerously(x?: number | null) {
  // 没有错误
  console.log(x!.toFixed());
}

就像其他类型断言一样,非空断言操作符 ! 不会改变代码的运行时行为。因此,只有在你确定值不会是 null 或 undefined 时,才应该使用 !。

枚举(Enums)

枚举是 TypeScript 向 JavaScript 添加的一个特性,它允许描述一个值,该值可以是某一组可能的命名常量中的一个。与大多数 TypeScript 特性不同,枚举不是对 JavaScript 的类型层面的扩展,而是语言和运行时的一部分。因此,这是一个你应该知道它存在的特性,但除非你确定需要使用它,否则最好暂时避免使用。你可以在枚举参考页面阅读更多关于枚举的信息。

// Numeric Enums
enum Direction {
  Up,
  Down,
  Left,
  Right,
}

// String enums
enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}

到此 TypeScript日常类型 就全部认识完了。