首页 > 解决方案 > 检查对象的类型

问题描述

我定义了这种类型

export interface Hostel {
    id: String;
}

我想检查一个对象是否来自该类型,但没有办法。我试过了

console.log ('************ ', (typeof result === 'Hostel'));
        console.log ('************ ', (typeof result === Hostel));
        console.log ('************ ', result instanceof Hostel);

我有这个错误:

'Hostel' only refers to a type, but is being used as a value here.

标签: javascriptnode.jstypescript

解决方案


Types (which includes interfaces) are only available during development and compile time and not during runtime. You need to use a class if you want to check the type during runtime.

export class Hostel {
    constructor(public id: String){};
}

const result = new Hostel("foo");

console.log(result instanceof Hostel) // this will return true

推荐阅读