Cache Keys Stay Type Safe At Compile Time

A Partial Record over literal endpoint keys tracks hit counts, so misspelled endpoints fail to compile and absent keys stay undefined instead of zero.

TypescriptData Fetching

Code

typescriptsnippet
21 lines
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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Inside the snippet

Count the function record as the entire surface area of Cache Keys Stay Type Safe At Compile Time.

Iteration happens inside for (const [endpoint, count] of Object.entries(hits)) — everything outside it runs once.

Putting it to use

Entry signature: function record(endpoint: Endpoint)

The demo output is labeled (unknown key absent:), so every printed line can be matched to the operation behind it.

Core lines

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

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `record` at load time.