主题
typeof 类型守卫
typeof 类型守卫用于在运行时判断值的 JavaScript 类型,并让 TypeScript 在分支内部缩小类型范围。
基本用法
typeof 常用于检查原始类型,例如 string、number、boolean、undefined、bigint 和 symbol。
ts
function printValue(value: string | number) {
if (typeof value === 'string') {
console.log(`String value: ${value.toUpperCase()}`)
} else {
console.log(`Number value: ${value.toFixed(2)}`)
}
}使用场景
- 处理联合类型
- 缩小
unknown - 在分支中安全调用不同类型的方法
例子
检查字符串类型
ts
function isString(value: unknown): value is string {
return typeof value === 'string'
}检查数字类型
ts
function isNumber(value: unknown): value is number {
return typeof value === 'number'
}处理联合类型中的不同类型
ts
type User = {
id: number
name: string
}
function processInput(input: string | number | User) {
if (typeof input === 'string') {
console.log(`Received a string: ${input}`)
} else if (typeof input === 'number') {
console.log(`Received a number: ${input}`)
} else {
console.log(`Received a user: ${input.name}`)
}
}局限性
typeof 只能判断 JavaScript 运行时暴露出来的基础类型信息,无法直接区分普通对象的具体结构。
对于对象类型,通常需要改用:
instanceofin- 自定义类型守卫
