Satisfies For Constrained Inference
Keep literal types while still checking a shape with satisfies, so you get validation and precise inference in the same declaration.
Code
type Route = { path: string; roles: readonly string[] };
// satisfies:校验形状,同时保留字面量类型(不是宽化成 Route)
const ROUTES = {
home: { path: '/', roles: ['guest'] },
admin: { path: '/admin', roles: ['admin'] },
} as const satisfies Record<string, Route>;
type RouteName = keyof typeof ROUTES;
function link(name: RouteName): string {
return ROUTES[name].path;
}
console.log(link('home'), link('admin'));
// 字面量类型保住了:roles 不是 string[] 而是 readonly ['admin']
const adminRoles = ROUTES.admin.roles;
console.log('roles literal:', adminRoles.join(','), adminRoles.length);
// 对照:类型注解会宽化字面量
const widened: Route = { path: '/x', roles: ['guest'] };
console.log('widened roles type is string[]:', Array.isArray(widened.roles));Output
Captured from a sandboxed run of this snippet in the build pipeline.
/ /admin
roles literal: admin 1
widened roles type is string[]: trueHow it works
Satisfies For Constrained Inference reduces to the function link.
Putting it to use
The main signature reads function link(name: RouteName)
The demo output is labeled (roles literal:, widened roles type is string[]:), so each line in the output traces back to its producing call.
Core lines
type RouteName = keyof typeof ROUTES;
return ROUTES[name].path;
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `link` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.