实现说明
satisfies 保留字面量推断可以归结为函数 link。
使用要点
- 演示输出是带标签的(
roles literal:、widened roles type is string[]:),每个操作都会留下自己的一行标注。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 link。
入口签名:function link(name: RouteName)
核心语句
type RouteName = keyof typeof ROUTES;
return ROUTES[name].path;
代码示例
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));