1

I have a React app written in Typescript. I am attempting to determine at runtime whether an object matches my Typescript interface.

Here are some options that won't work for me:

  • I do not want to write a typeguard since my interface is often changing and is large.
  • I already have, stored outside of my React app's src/ folder, a JSON representation of the interface's schema generated using the typescript-json-schema package. However, I cannot reference this JSON file since fs.readFileSync and other similar read functions do not work from browsers (this is a security feature; see here for one explanation).

Here is my current attempt to generate a runtime schema object using typescript-json-schema, then validate it using AJV:

  const program = TJS.getProgramFromFiles([resolve(FILE_PATH_TO_INTERFACE_DEFINITION)]);
  const schema = TJS.generateSchema(program, INTERFACE_NAME);
  const validate = new Ajv().compile(schema!);
  return validate(data);

FILE_PATH_TO_TYPE_DEFINITIONS is inside my React app's src/ directory.

The error with this specific code is type undefined not found when generating the schema on line 2. I'm looking for explanations/solutions for this particular error or other approaches that would work (since even when I tweak the code to avoid this particular error I run into other issues, which makes me think I'm missing something bigger about AJV or about typescript-json-schema.).

val1217
  • 21
  • 4

0 Answers0