TypeScript 是一种强类型的 JavaScript 超集,它引入了静态类型声明和面向对象编程的概念,可以大幅减少代码的错误率,同时提高代码的可维护性。在 TypeScript 中,对变量的类型进行正确的判断和识别是非常重要的,因此在本文中,我们将深入探讨如何在 TypeScript 中判断变量的类型。
基本类型判断
在 TypeScript 中,可以使用 typeof 关键字来判断基本类型的变量类型。以下是一些示例代码:
// www.javascriptcn.com code example
const num: number = 123
console.log(typeof num === 'number') // true
const str: string = 'hello'
console.log(typeof str === 'string') // true
const bool: boolean = true
console.log(typeof bool === 'boolean') // true
const undef: undefined = undefined
console.log(typeof undef === 'undefined') // true
const nul: null = null
console.log(typeof nul === 'object') // true
const obj: object = {}
console.log(typeof obj === 'object') // true
const sym: symbol = Symbol()
console.log(typeof sym === 'symbol') // true需要注意的是,对于 null 类型,typeof null 的结果是 'object',这是一个历史悠久的 JavaScript Bug,因此需要注意避免使用 typeof null === 'object' 这样的语句。
自定义类型判断
在 TypeScript 中,很多时候我们需要自定义类型判断,以便更好地识别变量的类型。此时可以使用 instanceof 关键字来进行判断。以下是一些示例代码:
// www.javascriptcn.com code example
class Person {
name: string
constructor(name: string) {
this.name = name
}
}
const person: Person = new Person('张三')
console.log(person instanceof Person) // true
class Animal {
name: string
constructor(name: string) {
this.name = name
}
}
const animal: Animal = new Animal('狗')
console.log(animal instanceof Person) // false
console.log(animal instanceof Animal) // true需要注意的是,使用 instanceof 进行类型判断时,需要确保输入的变量为具体的对象实例,否则可能无法正确判断类型。
类型联合判断
在 TypeScript 中,可以使用 | 符号来表示联合类型,如 number | string 表示一个既可以是数字又可以是字符串的变量类型。在判断联合类型变量类型时,可以使用 TypeScript 提供的类型保护语法,包括 typeof 和 instanceof 关键字、in 关键字、自定义类型保护函数等。以下是一些示例代码:
// www.javascriptcn.com code example
function format(strOrNum: string | number) {
if (typeof strOrNum === 'string') {
return strOrNum.toUpperCase()
}
if (typeof strOrNum === 'number' && strOrNum > 0) {
return '+' + strOrNum
}
}
console.log(format('hello')) // 'HELLO'
console.log(format(-1)) // undefined
console.log(format(1)) // '+1'// www.javascriptcn.com code example
class Bird {
name: string
wings: number
constructor(name: string, wings: number) {
this.name = name
this.wings = wings
}
}
class Fish {
name: string
fins: number
constructor(name: string, fins: number) {
this.name = name
this.fins = fins
}
}
function getAnimalDesc(animal: Bird | Fish) {
if (animal instanceof Bird) {
return `${animal.name} 有 ${animal.wings} 只翅膀`
}
if (animal instanceof Fish) {
return `${animal.name} 有 ${animal.fins} 条鱼鳍`
}
}
console.log(getAnimalDesc(new Bird('鹰', 2))) // '鹰 有 2 只翅膀'
console.log(getAnimalDesc(new Fish('鲨鱼', 5))) // '鲨鱼 有 5 条鱼鳍'// www.javascriptcn.com code example
type Person = {
name: string
age: number
}
type Dog = {
name: string
legs: number
}
function isPerson(animal: Person | Dog): animal is Person {
return 'age' in animal
}
function getDesc(animal: Person | Dog) {
if (isPerson(animal)) {
return `${animal.name} ${animal.age} 岁`
} else {
return `${animal.name} 有 ${animal.legs} 条腿`
}
}
console.log(getDesc({ name: '张三', age: 18 })) // '张三 18 岁'
console.log(getDesc({ name: '小狗', legs: 4 })) // '小狗 有 4 条腿'需要注意的是,在 getDesc 函数中,我们定义了一个名为 isPerson 的函数作为自定义类型保护函数,用于判断输入的变量是否为 Person 类型。当返回值为 true 时,TypeScript 就知道 animal 变量为 Person 类型,因此可以直接访问其 age 属性。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67ce4948e46428fe9e857880