返回

魔法般的类型转换:浅谈 Narrow Type

前端

从 as const 说起

在深入探讨 Narrow Type 之前,我们先来回顾一下 as const 的作用。

as const 运算符可以将一个变量标记为常量,使其值无法被重新赋值。例如:

const num: number = 10;
// error: Cannot assign to a constant.
num = 20;

使用 as const 可以让 TypeScript 对变量类型进行更严格的约束,从而避免不必要的赋值错误。

揭秘 Narrow Type

Narrow Type 是 TypeScript 中的一种类型约束,它可以将变量的类型范围缩小到更具体的类型。例如:

const num: number = 10;
// error: Cannot assign to a constant.
num = 'hello';

在上面的代码中,变量 num 被声明为 number 类型,但我们尝试将一个字符串值赋给它时,编译器报错了。这是因为 TypeScript 知道 num 是一个数字,而字符串不是数字,因此不允许这种赋值。

Narrow Type 可以帮助我们更精确地控制变量的类型,从而避免潜在的类型错误。

Narrow Type 的妙用

Narrow Type 不仅可以用于防止类型错误,还可以用于一些更高级的场景。例如:

1. 条件类型

条件类型可以根据某个条件来推导出一个新的类型。例如:

type IsString<T> = T extends string ? true : false;

function isString(value: any): IsString<typeof value> {
  return typeof value === 'string';
}

console.log(isString('hello')); // true
console.log(isString(10)); // false

在这个例子中,IsString 是一个条件类型,它根据 value 的类型推导出一个布尔值。isString 函数使用 IsString 类型来检查 value 是否是字符串。

2. 分组类型

分组类型可以将多个类型组合成一个新的类型。例如:

type Person = {
  name: string;
  age: number;
};

type Address = {
  street: string;
  city: string;
  state: string;
};

type PersonWithAddress = Person & Address;

const personWithAddress: PersonWithAddress = {
  name: 'John',
  age: 30,
  street: '123 Main Street',
  city: 'Anytown',
  state: 'CA'
};

在这个例子中,PersonWithAddress 是一个分组类型,它将 Person 和 Address 类型组合成了一个新的类型。personWithAddress 变量是一个 PersonWithAddress 类型的值,它具有 name、age、street、city 和 state 属性。

结语

Narrow Type 是 TypeScript 中一种强大的类型约束机制,它可以帮助我们更精确地控制变量的类型,从而避免潜在的类型错误。在本文中,我们探讨了 Narrow Type 的一些基本用法,包括条件类型和分组类型。通过这些用法,我们可以编写出更健壮、更易维护的 TypeScript 代码。