简体   繁体   中英

Javascript, validate object against exported type from npm package

I developed a ClI npm package with TS that consumes a configuration file from a given path.

> tool --config="./path/to/config"

The configuration file exports a single object which my tool imports.
Is there a way I can validate the imported object against a specific type definition?

The tool has exported type definitions so I could force users to create their configuration file using TS and just reference the successfully compiled JS file.

But, are there any other options? Would it be possible to have a JS file use a type from my CLI tool such that users would not have to install TSC wherever they wish to leverage my tool.

I came across Schemas, while writing this. Are they the best solution to my issue?

One option is to generate a json schema from your type definitions during the build step (using typescript-json-schema for example) and verify the config against such schema.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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