写路由、权限表这类配置时,直接给变量标注类型,常常会把具体值拓宽成联合类型。satisfies 可以检查结构,同时保留对象本身的字面量信息:
type Route = {
method: "GET" | "POST";
path: `/${string}`;
};
const routes = {
health: { method: "GET", path: "/health" },
login: { method: "POST", path: "/login" },
} satisfies Record<string, Route>;
const method = routes.health.method; // 仍然是 "GET"
把代码保存成 example.ts,用 TypeScript 4.9+ 执行 tsc --noEmit example.ts 就能检查。比如把 path 写成 health,或者把 method 写成 PUT,编译时会直接报错。配置对象需要后续按具体键做类型推断时,这个写法挺顺手。