Yasin

Yasin

Typescript keyof typeof写法

export const BREAKPOINTS = {
  sm: 640,
  md: 768,
  lg: 1024,
  xl: 1280,
  "2xl": 1536,
} as const;

export type Breakpoint = keyof typeof BREAKPOINTS;

这是 TypeScript 中的一种常用技巧,用于从一个常量对象(constant object)可以自动生成联合类型(Union Type)。

让我一步步为你拆解:

  1. typeof BREAKPOINTS:

    • 这个操作符会获取 BREAKPOINTS 这个变量的 TypeScript 类型
    • 结果类似于:{ readonly sm: 640; readonly md: 768; ... }
  2. keyof ...:

    • 这个操作符会提取一个对象类型中所有键名(key)的集合,形成一个字符串联合类型。
    • 在这个例子中,就是提取 sm, md, lg, xl, 2xl
  3. 最终结果: 即使你并没有手动写出 "sm" | "md" | "lg"...Breakpoint 类型自动变成了:

    type Breakpoint = "sm" | "md" | "lg" | "xl" | "2xl";
    

这种写法的好处: 这提供了单一数据源(Single Source of Truth)。如果你将来修改了 BREAKPOINTS 对象(例如添加了一个 xxl: 1600),Breakpoint 类型会自动更新,包含新的 "xxl",无需手动维护两处代码。