【问题标题】:check the type of an object [duplicate]检查对象的类型[重复]
【发布时间】:2020-04-27 03:54:57
【问题描述】:

我已经定义了这个类型

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.

【问题讨论】:

标签: javascript node.js typescript


【解决方案1】:

类型(包括接口)仅在开发和编译期间可用,而在运行时不可用。如果要在运行时检查类型,则需要使用class

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

const result = new Hostel("foo");

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

【讨论】:

    猜你喜欢
    • 2014-07-02
    • 2020-12-21
    • 2020-07-01
    • 2016-10-14
    • 1970-01-01
    • 2020-04-01
    • 2016-09-04
    • 2018-10-08
    相关资源
    最近更新 更多