json-schema-to-typescript icon indicating copy to clipboard operation
json-schema-to-typescript copied to clipboard

Add option for failing on unknown JSON Schema type

Open Winded opened this issue 3 years ago • 3 comments

Currently, the generator defaults to type { [k: string]: unknown; } if JSON Schema type is not a valid type. It would be helpful to have an option to make this fail the generation, i.e. throw an error instead of using this default value.

Winded avatar Jul 28 '22 13:07 Winded

@Winded would you please provide and example of schema that is translated to unknown typescript type?

cesarvspr avatar Oct 02 '22 16:10 cesarvspr

I modified the example JSON to have invalid type for a field:

{
  "title": "Person",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string"
    },
    "lastName": {
      "type": "asd"
    },
    "age": {
      "description": "Age in years",
      "type": "integer",
      "minimum": 0
    },
    "hairColor": {
      "enum": ["black", "brown", "blue"],
      "type": "string"
    }
  },
  "required": ["firstName", "lastName"]
}

This results in generated code:

/* tslint:disable */
/**
 * This file was automatically generated by json-schema-to-typescript.
 * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
 * and run json-schema-to-typescript to regenerate this file.
 */

export interface Person {
  firstName: string;
  lastName: {
    [k: string]: unknown;
  };
  /**
   * Age in years
   */
  age?: number;
  hairColor?: "black" | "brown" | "blue";
  [k: string]: unknown;
}

Winded avatar Oct 11 '22 10:10 Winded

Hi, looking a bit at this request. Does it make sense to add a 'strict' mode in the options and throw exception if we have a case of 'UNKNOWN'? or would that be too heavy handed?

I noticed there's also options.unknownAny. Should we still allow for those UNKNOWNs even in this new 'strict' mode?

tlahav avatar Oct 20 '22 01:10 tlahav