mrjono1 / joi-to-typescript

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

Cannot generate an error-free type with known and unknown keys with different values #470

Open CMunkyDev opened 1 month ago

CMunkyDev commented 1 month ago

Describe the bug Cannot generate an error-free type with known and unknown keys with different values

To Reproduce ExampleSchema.ts

import * as Joi from "joi"

export const examplesSchema = Joi.object({
    knownKey: Joi.string(),
})
.unknown(true)
.meta({ className: "Example", unknownType: Joi.object() })

Expected behavior A generated type without errors

export type Example = {
    [x: string]: object;
} & {
    knownKey?: string;
}
// or
export interface Example {
    [x: string]: typeof x extends 'knownKey' ? string : object;
}

Actual behavior Generated type has errors

export interface Example {
  [x: string]: object;
  knownKey?: string;
}

image Additional context It's not 100% necessary, and maybe there's a better way, but when you have a known key with a certain value type, and an unknown key that would have a different value type, I'm not seeing how I could write a Joi schema in a way that would get joi-to-typescript to make a type without errors.

For now, I've written a little helper that runs after convertFromDirectory to add a @ts-expect-error on the line above the offending line, as it seems typescript still works fine and VS Code suggests the right stuff; but that's definitely only a temporary solution. I might be able to make a PR but figured I'd put this issue in.

please let me know if I'm just being silly. Thanks!