← 中文资源

简体中文版本

缓存键在编译期保持类型安全

Partial<Record<Endpoint, number>> 用路径字面量做缓存键:拼错端点编译报错,未计数的键保持 undefined 而不是悄悄变 0。

阅读英文原文

运行结果

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

/users = 2
/orders/:id = 1
unknown key absent: true

实现说明

全部逻辑都在函数 record中。 for (const [endpoint, count] of Object.entries(hits)) 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 跑完文件,输出里会留下标记——unknown key absent:。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 record。

主要签名是 function record(endpoint: Endpoint)

核心语句

hits[endpoint] = (hits[endpoint] ?? 0) + 1;

代码示例

type Endpoint = "/users" | "/orders" | "/orders/:id";

// 键即路径字面量:Cache 按形状逐条记录命中次数
type CacheHits = Partial<Record<Endpoint, number>>;

const hits: CacheHits = {};
function record(endpoint: Endpoint): void {
  hits[endpoint] = (hits[endpoint] ?? 0) + 1;
}

record("/users");
record("/users");
record("/orders/:id");

// 遍历已计数的键:entries 只返回出现过的端点
for (const [endpoint, count] of Object.entries(hits)) {
  console.log(endpoint, "=", count);
}

// 未出现的键不存在:undefined 而不是 0
console.log("unknown key absent:", hits["/orders"] === undefined);