TypeScript 对象类型判定: typeof, instanceof 和 Object.prototype.toString.call()
在 TypeScript 中,可以使用 'typeof' 和 'instanceof' 运算符来进行对象类型判定。
- 使用 'typeof' 运算符
'typeof' 运算符可以用来判断一个变量的类型是否为特定的类型,如 'string'、'number'、'boolean'、'undefined'、'function' 等。
示例:
const str = 'hello';
if (typeof str === 'string') {
console.log('str is a string');
}
- 使用 'instanceof' 运算符
'instanceof' 运算符可以用来判断一个对象是否属于某个类的实例。
示例:
class Person {}
const person = new Person();
if (person instanceof Person) {
console.log('person is an instance of Person class');
}
除了以上两种方法,还可以使用 'Object.prototype.toString.call()' 方法来获取一个对象的类型。示例:
const obj = { name: 'Tom' };
console.log(Object.prototype.toString.call(obj)); // [object Object]
原文地址: https://www.cveoy.top/t/topic/lL4a 著作权归作者所有。请勿转载和采集!