Coding Hao

详解 TypeScript satisfies 关键字

2024年6月12日 (1年前)

TypeScript satisfies 关键字介绍

在 TypeScript 中,satisfies 是一个用于类型约束的关键字,它允许你在不改变变量类型的情况下,确保该变量满足某个特定的类型或接口,并且在编译时提供更严格的类型安全保证。 这个关键字在 TypeScript 4.9 版本中引入,主要用于增强类型安全性和代码可读性。使用场景:

  • 需要类型检查但又想保持精确类型推断时
  • 处理对象字面量时需要验证结构但保留具体值的类型
  • 处理混合类型数组时需要保证类型安全

基本语法

const variable = value satisfies Type;
  • value: 变量的实际值。
  • Type: 需要满足的类型或接口。
  • 作用:确保 value 满足 Type 的类型约束,但不会改变 value 的推断类型。

使用场景

(1) 确保类型安全

const colors = {
  red: "#FF0000",
  green: "#00FF00",
  blue: "#0000FF",
} satisfies Record<string, string>;
  • 这里 colors 被约束为 Record<string, string> ,确保所有属性值都是字符串。
  • 如果某个属性值不是字符串,TypeScript 会报错。

(2) 保留字面量类型

字面量类型,简单来说就是直接把值当数据类型。eg: const name:'jack' | 'tom' = 'tom'

const user = {
  name: "Alice",
  age: 25,
} satisfies { name: string; age: number };
  • user 的类型仍然是 { name: string; age: number },而不是更宽泛的类型(如 object)。
  • 同时确保 user 满足 { name: string; age: number } 的结构。

(3) 联合类型约束

const result = Math.random() > 0.5 ? "success" : 0 satisfies string | number;
  • result 只能是 string 或 number 类型,其他类型会报错

实际应用

(1) 配置对象验证

确保 config 对象包含 port 和 host 属性,且类型正确:

const config = {
  port: 8080,
  host: "localhost",
} satisfies { port: number; host: string };

(2) 函数返回值约束 确保函数返回值只能是 string 或 number:

function getValue() {
  return Math.random() > 0.5 ? "success" : 0 satisfies string | number;
}

(3) 复杂类型约束 确保 response 的结构和类型符合预期:

const response = {
  status: 200,
  data: { id: 1, name: "Alice" },
} satisfies { status: number; data: { id: number; name: string } };