简体   繁体   English

如何检查typescript中的变量类型

[英]How to check variable type in typescript

I have a JS object of type any and i want to check its content and get value in correct type so i imagined a function like this我有一个 any 类型的 JS object,我想检查它的内容并获取正确类型的值,所以我想象了一个像这样的 function

function getRequiredField<T>(config: any, name: string): T {
    if (config[name] === undefined) throw new Error(`Required field ${name} is missing`);
    return config[name] as T;
}

And its working as i want, but now i would like to check the typeof config[name] and be sure it is the same as T. How can i do this?它按我想要的方式工作,但现在我想检查 typeof config[name] 并确保它与 T 相同。我该怎么做?

Thanks for your help.谢谢你的帮助。

You can use instanceof operator to check if it's type instance of T or not.您可以使用instanceof运算符来检查它是否是T的类型实例。

config[name] instanceof Sprite;

This will return Boolean primary type value.这将返回Boolean主要类型值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM