javascript - 检查对象的类型
问题描述
我定义了这种类型
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.
解决方案
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
推荐阅读
- javascript - 如何更改变量中的一项设置
- sql-server - 在唯一找到一行的两列上建立索引
- r - 在 R 中通过扭曲将长数据集转换为宽数据集?
- d3.js - 将映射应用于附加数据
- elasticsearch - 比较日期的脚本
- node.js - 创建执行外部 api 调用的中间件
- node.js - 我无法在 Heroku 上部署 Alexa 技能(使用 jovo 构建)
- javascript - 粘性侧边栏不粘在 Vue.js 中
- c# - 我可以压缩这个 if 语句吗?
- xamarin.forms - Xamarin.Forms + Xamarin.ios Entityframework Core 2.1.1 构建错误