TypeScript判断对象类型的四种方式
warning:
这篇文章距离上次修改已过439天,其中的内容可能已经有所变动。
在TypeScript中,你可以通过以下四种方式来判断一个对象的类型:
- 使用
typeof操作符。 - 使用
instanceof操作符。 - 使用
constructor属性。 - 使用
Object.prototype.toString方法。
以下是每种方式的示例代码:
- 使用
typeof操作符:
function isString(obj: any): obj is string {
return typeof obj === "string";
}- 使用
instanceof操作符:
class MyClass {}
function isMyClass(obj: any): obj is MyClass {
return obj instanceof MyClass;
}- 使用
constructor属性:
function isArray(obj: any): obj is any[] {
return obj && obj.constructor === Array;
}- 使用
Object.prototype.toString方法:
function isDate(obj: any): obj is Date {
return Object.prototype.toString.call(obj) === "[object Date]";
}这四种方法各有利弊,typeof适合基础类型判断,instanceof适合判断类的实例,constructor可能会被修改,而Object.prototype.toString是最可靠的方法。
评论已关闭