实现说明
底层就是函数 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(' < '));