← 中文资源

简体中文版本

satisfies 校验只读排序表

satisfies 让查找表对照目标形状逐行校验、同时保留字面量收窄:rank 类型仍是 0 | 1 | 2;联合里新增成员而表里缺行时编译期即报错,排序依赖已校验的 rank。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

now rank: 0
order: now < soon < later

实现说明

底层就是函数 order。

使用要点

  • 跑完文件,输出里会留下标记——now rank:、order:。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件在加载时定义 order。

主要签名是 const order = (Object.keys(priorities)

核心语句

.sort((a, b) => priorities[a].rank - priorities[b].rank);

代码示例

type Priority = 'now' | 'soon' | 'later';

// satisfies validates against PriorityTable while keeping exact literals:
// the variable keeps its own narrower type instead of widening.
const priorities = {
  now: { rank: 0, label: 'drop everything' },
  soon: { rank: 1, label: 'this week' },
  later: { rank: 2, label: 'backlog' },
} satisfies Readonly<Record<Priority, { rank: number; label: string }>>;

// Literal types survive: this reads as 0 | 1 | 2, not number.
type Rank = (typeof priorities)[Priority]['rank'];
const rank: Rank = priorities.now.rank;
console.log('now rank:', rank);

// The table is exhaustively checked: adding 'urgent' to the union below
// breaks compilation until a row exists for it — swap the comment to see:
// type Priority2 = Priority | 'urgent';
// type Strict = Readonly<Record<Priority2, { rank: number; label: string }>>;
// const _wider: Strict = priorities; // error names 'urgent' as missing

// Sorting stays correct: rank comes from checked rows, not guesses.
const order = (Object.keys(priorities) as Priority[])
  .sort((a, b) => priorities[a].rank - priorities[b].rank);
console.log('order:', order.join(' < '));