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.
Code
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: trueInside 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
Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `record` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.