掌握 TypeScript 中的文字类型:true as const 与 true
在 TypeScript 中,这两种说法之间存在显著差异:
仅供参考,我从 React router v7 中选择了这些示例。
让我们通过详细的解释和例子来分析其中的区别
TypeScript 中的“as const”断言是一种告诉 TypeScript 编译器将值视为其文字类型而不是一般类型的方式。
在这种情况下,“true as const” 意味着“hydrate” 的类型将是文字“true”,而不是“boolean”。它本质上将 hydrate 的值锁定为“true”。
例子:
interface ClientLoader {
hydrate: true; // The type of hydrate is set to the literal value `true`
}
const clientLoader: ClientLoader = {
hydrate: true as const,
};
clientLoader.hydrate = true; // This is valid
// clientLoader.hydrate = false; // Error: Type 'false' is not assignable to type 'true'如果没有 `as const` 断言,TypeScript 会将 `hydrate` 的类型推断为 `boolean`。这意味着 `hydrate` 可以被赋予任何 `boolean` 值 `(true 或 false)`。
例子:
interface ClientLoader {
hydrate: boolean; // The type of hydrate is set to `boolean`
}
const clientLoader: ClientLoader = {
hydrate: true,
};
clientLoader.hydrate = true; // This is valid
clientLoader.hydrate = false; // This is also valid为什么用作 const?
type Status = 'pending' | 'completed' | 'failed'; const status: Status = 'pending'; // 'pending' is a valid value // status = 'in-progress'; // Error: Type '"in-progress"' is not assignable to type 'Status' // With 'as const' const taskStatus = 'pending' as const; // Now taskStatus is narrowed down to the literal type 'pending'
结论
这使得 const 成为一个有用的工具,可以在 TypeScript 代码中更精确地输入并强制执行更严格的值约束。