TypeScript Satisfies Config Inference
Constrain config objects with the satisfies operator, keeping literal inference for keys while enforcing the target shape.
Code
type RouteConfig = Record<string, {
methods: readonly ('GET' | 'POST')[];
rateLimit?: number;
}>;
const routes = {
'/healthz': { methods: ['GET'] },
'/orders': { methods: ['GET', 'POST'], rateLimit: 120 },
'/admin/purge': { methods: ['POST'], rateLimit: 5 },
} satisfies RouteConfig;
// satisfies 保留字面量推断:键类型是三个具体路径而非 string
type RoutePath = keyof typeof routes;
const critical: RoutePath = '/admin/purge';
// 联合收窄到真实出现的值
type AllowedMethod = (typeof routes)['/orders']['methods'][number];
const m: AllowedMethod = 'POST';
function routeLimit(path: RoutePath): number {
return routes[path].rateLimit ?? 60;
}
console.log(critical, m, routeLimit('/healthz'), routeLimit('/orders'));
// 对照:类型注解会拓宽字面量,键类型退化为 string
const widened: RouteConfig = {
'/healthz': { methods: ['GET'] },
};
type WidenedKey = keyof typeof widened; // string
const anyPath: WidenedKey = '/anything-goes';Report a problem with this exampleOpens a pre-filled issue on GitHub.