TCMiranda/joi-extract-type

possibly undefined value whereas `.default` is defined

Closed this issue · 10 comments

Hello!

Thanks so much for this project.

I think I catch an unexpected behavior:

My object definition is:

Joi.object({
  page: Joi.number().default(0),
}).required()

Then when I extract type I get this type:

Map<{
    page?: number | undefined;
} & {}>

As far as I know, page can't be undefined after joi validation. Am I right?

I don't understand why the extracted type would be:

{
  page: number
}

Why would we allow an empty object {}?

And don't we want Joi.validate({ }, schema) to be accepted?

I think the confusion here is around whether the extracted type is supposed to model the object going into Joi.validate() or the object that comes out when validation is successful. For example:

const schema = Joi.object({
  page: Joi.number().default(0),
}).required();
const { value } = schema.validate({});

The object being passed into validate can be empty, but the one that comes out can't -- in this case it would be { page: 0 }. I would expect the extracted type to model the validated object, so:

{
    page: number;
}

@TCMiranda I think @mrozekma is right.
I hope this issue can be addresses, as .default(xx) is a very common pattern

Thanks everybody, I made it required.
Just published 15.0.2, could you see if it fits?

@TCMiranda did this ever land? I'm still seeing the following:

const enabledConfigSchema = Joi.object({ enabled: Joi.boolean().default(true) })
export type EnabledConfig = Joi.extractType<typeof enabledConfigSchema>
// enabled can still be undefined, even though it has a default
pke commented

@TCMiranda this does indeed still not work in 15.0.8. Was the patch ever released to npm? I can't find any tags on this repo nor releases.