ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.43k stars 30 forks source link

Custom JSON Schema type #107

Closed flugg closed 1 year ago

flugg commented 1 year ago

Greetings!

Superb library - we would love to utilise it in our projects, however, we've created a custom type for our superset of JSON Schema to support our custom vocabularies (including Ajv's $data reference etc.). However, the FromSchema type complaints about the provided type being incompatible with this package's own JSONSchema type.

Any idea how to solve this? Would it be possible to add an option for providing a custom JSON Schema type in some way? Or simply a non-strict version of FromSchema allowing any object?

ThomasAribart commented 1 year ago

Hello @flugg ! FYI, FromSchema already accepts custom types but you would need at least one property in common with JSONSchema:

type MyCustomSchema1 = {
  type: "object";
  custom: 'option';
};

// works fine
type Test1 = FromSchema<MyCustomSchema1>;

type MyCustomSchema2 = {
  custom: 'option';
};

// errors
type Test2 = FromSchema<MyCustomSchema2>;

Maybe I can add & Record<string, unknown> to the constraint, I'll see what I can do.

ThomasAribart commented 1 year ago

(sorry misclick, didn't want to close)

flugg commented 1 year ago

Thanks for the reply @ThomasAribart! I did some checks, and when using FromSchema with a literal schema type (generated from the custom JSON Schema type) everything works. But when trying to create a type that extends FromSchema with type safety for our custom JSON Schema type, it fails. For instance:

type CustomFromSchema<S extends CustomJsonSchema> = FromSchema<S>;
flugg commented 1 year ago

I think I actually found a solution for this:

type CustomFromSchema<S extends CustomJsonSchema> = FromSchema<S extends JsonSchema ? S : never>;
ThomasAribart commented 1 year ago

Yes, indeed you can cast like this :) Can I close this issue ?

flugg commented 1 year ago

Absolutely, this solves my problems. Don't know if this is something you want to add to the documentation or not? Although I guess people interested will find this issue

ThomasAribart commented 1 year ago

Sure I'll add some docs in the FAQ 👍

ThomasAribart commented 1 year ago

@flugg You can now use the ExtendedJSONSchema and FromExtendedSchema types to use JSON Schema extensions:

Cf https://github.com/ThomasAribart/json-schema-to-ts#extensions