mrjono1 / joi-to-typescript

Convert Joi Schemas to TypeScript interfaces
MIT License
124 stars 39 forks source link

Wraps function types in additional brackets to prevent broken union types #400

Closed cmaster11 closed 7 months ago

cmaster11 commented 8 months ago

E.g. take this schema:

export const AlternativesWithFunctionSchema = Joi.alternatives([
  Joi.function().minArity(2),
  Joi.object({
    json: Joi.any().required()
  }),
  Joi.object({
    raw: Joi.string().required()
  })
]).meta({ className: 'AlternativesWithFunctionInterface' });

Without brackets, a chain would have become

(...args: any[]) => any | {
  json: any;
} | {
  raw: string;
};

In this type, the whole any | { json: any; } | { raw: string; } is the return type of the function, which is wrong.

With brackets, it will be:

export type AlternativesWithFunctionInterface = ((...args: any[]) => any) | {
  json: any;
} | {
  raw: string;
};

There could be some more advanced logic to figure out if we want the brackets or not depending if we're using a union or not, but I feel it is even safer in general to just wrap function types in brackets given the "unsupported" nature of the Function type.

Note: this will conflict on merge with https://github.com/mrjono1/joi-to-typescript/pull/401. I'll take care of it if merged. Probably one test will fail.

codecov[bot] commented 8 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Comparison is base (e80f93f) 98.69% compared to head (f7c6bf9) 98.69%.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #400 +/- ## ======================================= Coverage 98.69% 98.69% ======================================= Files 9 9 Lines 535 535 Branches 206 206 ======================================= Hits 528 528 Misses 7 7 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.