返回

TypeScript 中的 Narrowing

前端

TypeScript 中的 Narrowing 指的是在类型系统中缩小变量或表达式的类型。这可以帮助我们更准确地指定变量和表达式的类型,从而提高代码的可读性和可维护性。Narrowing 的本质是通过各种方式排除不可能的类型,从而使变量或表达式的类型更加具体和准确。

TypeScript 中有各种方式可以进行 Narrowing,包括:

  • 类型保护 (Type Guards) :类型保护是一种用于检查变量或表达式的类型是否满足特定条件的机制。类型保护可以是函数、类型谓词或类型注解。

  • 条件类型 (Conditional Types) :条件类型是一种根据条件来推断类型的方式。条件类型可以用来根据变量或表达式的值来缩小其类型。

  • 辨别联合 (Discriminated Unions) :辨别联合是一种特殊的联合类型,其中每个成员都有一个共同的属性,称为辨别属性。通过检查辨别属性的值,我们可以缩小联合类型的类型。

  • 穷举性检查 (Exhaustiveness Checking) :穷举性检查是一种确保所有可能的情况都被处理的机制。在 TypeScript 中,可以使用 switch 语句或 if 语句来进行穷举性检查。

通过使用 Narrowing,我们可以提高代码的可读性和可维护性,并减少错误的发生。以下是一些 Narrowing 的示例:

  • 使用 typeof 操作符进行类型保护
function isString(x: unknown): x is string {
  return typeof x === "string";
}

const str: string = "Hello, world!";
if (isString(str)) {
  console.log(str.toUpperCase()); // "HELLO, WORLD!"
}
  • 使用 in 操作符进行类型保护
interface Person {
  name: string;
  age: number;
}

function isPerson(x: unknown): x is Person {
  return "name" in x && "age" in x;
}

const person: Person = { name: "John Doe", age: 30 };
if (isPerson(person)) {
  console.log(person.name); // "John Doe"
  console.log(person.age); // 30
}
  • 使用条件类型进行类型缩小
type IsString<T> = T extends string ? true : false;

const str: IsString<"Hello, world!"> = true;
const num: IsString<123> = false;
  • 使用辨别联合进行类型缩小
interface Animal {
  type: "dog" | "cat";
}

function makeSound(animal: Animal): string {
  switch (animal.type) {
    case "dog":
      return "Woof!";
    case "cat":
      return "Meow!";
  }
}

const dog: Animal = { type: "dog" };
const cat: Animal = { type: "cat" };

console.log(makeSound(dog)); // "Woof!"
console.log(makeSound(cat)); // "Meow!"

希望这篇文章能帮助你更好地理解和使用 TypeScript 中的 Narrowing。如果你有兴趣了解更多关于 TypeScript 的内容,可以查阅官方文档或其他相关资源。