MasterScrat MasterScrat - 1 month ago 12
TypeScript Question

Check if an object implements an interface at runtime with TypeScript

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.

Question: is there a way to use this declaration to check the correctness of the file I load? ie that I do not have unexpected properties?

Answer

No.

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

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