ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.44k stars 31 forks source link

How to type input for `FromSchema` correctly? #69

Closed winston0410 closed 2 years ago

winston0410 commented 2 years ago

I have the following type of a helper function. I am trying to use JSONSchema here to fulfil the constraint of FromSchema.

type MkMiddy = <Res>(handler: Handler, inputSchema?: JSONSchema) => Lambda.ValidatedAPIGatewayProxyHandlerV2<FromSchema<typeof inputSchema>, Res>

However, Typescript is complaining for this:

error TS2589: Type instantiation is excessively deep and possibly infinite.

Based on the doc, https://github.com/ThomasAribart/json-schema-to-ts/blob/HEAD/documentation/FAQs/can-i-assign-jsonschema-to-my-schema-and-use-fromschema-at-the-same-time.md, it is incorrect to use both types together, so what type should I provide there instead? unknown doesn't work

ThomasAribart commented 2 years ago

Hello @winston0410,

Indeed, using FromSchema directly on JSONSchema won't work (it will return never or unknown since v2).

What you actually want is to exploit the strict type of your inputSchema input. To do this, you have to add a generic type to your util:

type MkMiddy = <InputSchema extends JSONSchema | undefined, Res>(handler: Handler, inputSchema?: InputSchema) =>
  Lambda.ValidatedAPIGatewayProxyHandlerV2<InputSchema extends JSONSchema ? FromSchema<InputSchema> : any, Res>

If there is still an error, you can try to extract the input type in the default value of another generic type:

type MkMiddy = <
  InputSchema extends JSONSchema | undefined,
  Res,
  Input = InputSchema extends JSONSchema ? FromSchema<InputSchema> : any
>(handler: Handler, inputSchema?: InputSchema) =>
  Lambda.ValidatedAPIGatewayProxyHandlerV2<Input, Res>
ThomasAribart commented 2 years ago

Hi @winston0410 ! Can I close this issue ?