如何在TypeScript中判断对象是否为自定义Hostel接口类型?
这个问题其实是TypeScript新手常踩的坑——TypeScript的interface只是编译时的类型标记,在代码编译成JavaScript后,这些类型信息会被完全擦除,运行时根本不存在Hostel这个值,这就是你看到报错'Hostel' only refers to a type, but is being used as a value here.的原因。
typeof只能判断JavaScript原生的基本类型(string、number、boolean等),instanceof则是用来判断对象是否是某个类的实例,但interface不是类,所以这两种方法都用不了。下面给你几个可行的解决方案:
1. 自定义类型守卫函数(最推荐,适配interface场景)
既然运行时没有类型信息,我们就通过检查对象的结构来判断它是否符合Hostel的定义,同时用TypeScript的类型谓词让编译器也能识别这个判断结果:
export interface Hostel { id: string; // 注意这里建议用小写的`string`(TypeScript的基础类型),而不是大写的`String`(构造函数) } // 类型守卫函数:返回true时,TypeScript会认定obj是Hostel类型 function isHostel(obj: unknown): obj is Hostel { // 先排除非对象的情况 if (typeof obj !== 'object' || obj === null) { return false; } // 检查是否包含id属性,且id是string类型 return 'id' in obj && typeof (obj as Hostel).id === 'string'; } // 使用示例 const result = { id: 'hostel-001' }; console.log(isHostel(result)); // 输出 true const invalidObj = { name: 'My Hostel' }; console.log(isHostel(invalidObj)); // 输出 false
这个函数不仅能在运行时做判断,还能让TypeScript在后续代码中自动推断类型——比如你写if (isHostel(result)) { console.log(result.id) }时,编译器会知道result.id是存在的string类型。
2. 把interface改成class(适用于可控实例场景)
如果你能把Hostel从interface改成class,那就能用instanceof了,因为class在运行时是真实存在的构造函数:
export class Hostel { constructor(public id: string) {} } // 只有通过new创建的实例才会触发instanceof为true const result = new Hostel('hostel-001'); console.log(result instanceof Hostel); // 输出 true // 注意:即使结构一致的普通对象,instanceof也会返回false const plainObj = { id: 'hostel-001' }; console.log(plainObj instanceof Hostel); // 输出 false
这种方法适合你能控制对象创建方式的场景,如果是从API、本地存储等地方拿到的普通对象,还是用类型守卫更合适。
3. 扩展复杂类型的检查(如果Hostel有更多属性)
如果Hostel还有其他可选或必填属性,可以在类型守卫里补充对应的检查逻辑:
interface Hostel { id: string; name: string; capacity?: number; // 可选属性 } function isHostel(obj: unknown): obj is Hostel { if (typeof obj !== 'object' || obj === null) return false; const hostel = obj as Hostel; // 检查必填属性,再处理可选属性 return typeof hostel.id === 'string' && typeof hostel.name === 'string' && (hostel.capacity === undefined || typeof hostel.capacity === 'number'); }
内容的提问来源于stack exchange,提问作者Sandro Rey

