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';Output
Captured from a sandboxed run of this snippet in the build pipeline.
/admin/purge POST 60 120The flow from top to bottom
TypeScript Satisfies Config Inference is built around the function routeLimit.
Applying it
The primary signature is function routeLimit(path: RoutePath)
Statements that matter
return routes[path].rateLimit ?? 60;
type WidenedKey = keyof typeof widened; // string
const anyPath: WidenedKey = '/anything-goes';
type RoutePath = keyof typeof routes;
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `routeLimit` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.