TCMiranda / joi-extract-type

Provides native type extraction from Joi schemas for Typescript
MIT License
151 stars 27 forks source link

Possibility to get type Record<string, T> #30

Closed lonewarrior556 closed 4 years ago

lonewarrior556 commented 4 years ago

Assuming you have an item where you don't know the key names but know the values.

In joi this looks like this

const schema = Joi.object().pattern(Joi.string(), Joi.number())
schema.validate({a: 1}) // ok
schema.validate({a: 10, b: 20}) // ok
schema.validate({a: 10, b: '20'}) // fail

But when you extract the type

// should be Record<string, number>
type A = Joi.extractType<typeof schema> //  unknown 

Is it doable to get this to work?

ps. I just found this lib it is awesome, will look to get involved once I figure out just how you do this

lonewarrior556 commented 4 years ago

NM Some help required but this works.

const schema = Joi.object<Record<string, number>>({}).pattern(Joi.string(), Joi.number())
schema.validate({a: 1}) // ok
schema.validate({a: 10, b: 20}) // ok
schema.validate({a: 10, b: '20'}) // fail

const a: A = {};
a.test1 = 10; //ok
a.test2 = '10'; // not assignable to type 'number'