实现说明
全部逻辑都在函数 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);