检查对象是否在运行时使用TypeScript实现接口 [英] Check if an object implements an interface at runtime with TypeScript

查看:294
本文介绍了检查对象是否在运行时使用TypeScript实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在运行时加载JSON配置文件,并使用接口来定义其预期结构:

I load a JSON configuration file at runtime, and use an interface to define its expected structure:

interface EngineConfig {
    pathplanner?: PathPlannerConfig;
    debug?: DebugConfig;
    ...
}

interface PathPlannerConfig {
    nbMaxIter?: number;
    nbIterPerChunk?: number;
    heuristic?: string;
}

interface DebugConfig {
    logLevel?: number;
}

...

这样便于访问各种属性,因为我可以使用自动填充等。

This makes it convenient to access the various properties since I can use autocompletions etc.

问题:有没有办法使用此声明来检查我加载的文件的正确性?即我没有意外的属性?

推荐答案


否。

No.

目前,类型仅在开发和编译期间使用。
类型信息不会以任何方式转换为已编译的
JavaScript代码。

Currently, types are used only during development and compile time. The type information is not translated in any way to the compiled JavaScript code.

来自 https://stackoverflow.com/a/16016688/318557 ,正如@JasonEvans所指出的那样

From https://stackoverflow.com/a/16016688/318557, as pointed out by @JasonEvans

这篇关于检查对象是否在运行时使用TypeScript实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆