TypeScript 类型判定: typeof 和 instanceof 详解
在 TypeScript 中,可以使用 'typeof' 和 'instanceof' 进行类型判断。
- 'typeof' 运算符
'typeof' 运算符可以用于判断一个值的类型,它会返回一个字符串表示该值的类型。常见的类型有:
- 'string':字符串类型
- 'number':数值类型
- 'boolean':布尔类型
- 'undefined':未定义类型
- 'object':对象类型,包括数组、函数、null 等
- 'function':函数类型
示例:
const str: string = 'Hello';
const num: number = 123;
const bool: boolean = true;
const obj: { name: string } = { name: 'Tom' };
const arr: number[] = [1, 2, 3];
console.log(typeof str); // 'string'
console.log(typeof num); // 'number'
console.log(typeof bool); // 'boolean'
console.log(typeof obj); // 'object'
console.log(typeof arr); // 'object'
注意,使用 'typeof' 判断数组类型时,会返回 'object',而不是 'array'。
- 'instanceof' 运算符
'instanceof' 运算符可以用于判断一个对象是否是某个类的实例。示例:
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
const person = new Person('Tom');
console.log(person instanceof Person); // true
console.log(person instanceof Object); // true
console.log(person instanceof Array); // false
注意,使用 'instanceof' 判断基本类型时,会报错:
const str: string = 'Hello';
console.log(str instanceof String); // 报错
因为字符串类型是基本类型,而不是对象类型。
原文地址: https://www.cveoy.top/t/topic/lL4p 著作权归作者所有。请勿转载和采集!