openapi-typescript-codegen icon indicating copy to clipboard operation
openapi-typescript-codegen copied to clipboard

WORK IN PROGRESS: add type guards

Open tibbe opened this issue 3 years ago • 0 comments

Add a type guards i.e. dynamic validation of the JSON returned from the server. This makes the generated code type safe (before it could be missing fields, despite what the TypeScript types say).

This is a WIP PR put here for comments. The general approach I had in mind:

  • Add a flag for this feature (e.g. --useTypeGuards). I'm not attached to the name.
  • Generate isModel type guard function for each generated model.
  • In the generated service, call isModel before returning the result. Raise some exception if validation fails (or fail some promise).
  • If the flag is set, remove the unsafe cast to Model that exists today.

Is this feature of interest?

There's still lots to do, mainly made difficult by Handlebars. Type checking is a recursive process (e.g. when validating an array property using a validate partial we'd like to call validate on each element) so we'd like to call a partial with dynamic arguments, which isn't possible in Handlebars AFAIK. I will need to find a workaround.

tibbe avatar Aug 12 '22 10:08 tibbe