any 和 unknown 和 never 和 void 的差异
| 特性 | any | unknown | never | void |
|---|---|---|---|---|
| 含义 | 任意类型 | 未知类型 | 不可能的值 | 无返回值 |
| 类型安全 | ❌ 不安全 | ✅ 安全 | ✅ 安全 | ✅ 安全 |
| 可赋值给 | 任何类型 | 需要断言 | 任何类型 | void/any |
| 可接受值 | 任何值 | 任何值 | 无值 | undefined(严格模式下无) |
| 主要用途 | 迁移旧代码 | 安全接收未知值 | 不可能的情况 | 函数无返回值 |
// 放弃所有类型安全
let anything: any = "hello";
anything = 42; // ✅
anything.foo.bar(); // ❌ 运行时错误,编译时不报错
const num: number = anything; // ✅ 可以赋值给任何类型
// 必须先进行类型检查
let uncertain: unknown = "hello";
// uncertain.toUpperCase(); // ❌ 错误:必须先检查类型
if (typeof uncertain === "string") {
uncertain.toUpperCase(); // ✅ 类型收窄后安全
}
// const str: string = uncertain; // ❌ 不能直接赋值
const str: string = uncertain as string; // ✅ 需要类型断言
// 表示永远不会发生的值
function throwError(): never {
throw new Error("失败"); // 永不返回
}
function infiniteLoop(): never {
while (true) {} // 永不退出
}
// let x: never = 42; // ❌ 不能赋值任何值
let num: number = throwError(); // ✅ never可赋给任何类型
// 函数没有返回值(或返回undefined)
function logMessage(): void {
console.log("Hello"); // 隐式返回undefined
}
function explicitVoid(): void {
console.log("Hello");
return undefined; // 显式返回undefined
}
// let x: void = 10; // ❌ 严格模式下不能赋值number
let x: void = undefined; // ✅ 可以赋值为undefined
类型安全层级(从左到右越来越安全):any → unknown → 具体类型/void → never
赋值关系: 1. any → 可以赋给 → 所有类型 2. unknown → 需要检查 → 可以赋给 3. void → 可以赋给 → void/any 4. never → 可以赋给 → 所有类型