如何在 TypeScript 中判断变量类型:typeof、instanceof 和自定义检查
大家好!我刚开始学习 TypeScript,遇到了一个问题:如何在程序运行时判断变量的类型?在普通 JavaScript 中,我使用 `typeof`,但在 TS 中它并不总是按我预期的方式工作。
以下是一个让我困惑的代码示例:
```typescript
let value: string | number = "hello";
// 尝试检查类型
if (typeof value === "string") {
console.log(value.toUpperCase()); // 有效
}
value = 42;
if (typeof value === "number") {
console.log(value.toFixed(2)); // 有效
}
// 但对于对象来说更复杂
interface User {
name: string;
age: number;
}
interface Admin {
name: string;
role: string;
}
function processUser(user: User | Admin) {
// 如何在这里判断是 User 还是 Admin?
if (typeof user === "object") { // 这没有帮助
// 如何获取具体类型?
}
}
```
我明白 TypeScript 是 JS 的超集,类型只在编译阶段存在。