joi icon indicating copy to clipboard operation
joi copied to clipboard

Extracting types from a Joi schema

Open AGrabovajFitA opened this issue 1 year ago • 8 comments

Support plan

  • is this issue currently blocking your project? (yes/no): no
  • is this issue affecting a production system? (yes/no): no

Context

  • node version: >= 16.14.0
  • module version: joi -> 17.6.0
  • environment (e.g. node, browser, native): all
  • used with (e.g. hapi application, another framework, standalone, ...): standalone
  • any other relevant information: no

What problem are you trying to solve?

As we are already creating the Joi schema we don't have to write the interface for it's value type. It can be inferred from the schema itself.

// the type of the schema at this point is Joi.ObjectSchema<any>
const schema = Joi.object({
  username: Joi.string().required(),
  password: Joi.string().required(),
});

// we'd like to be able to extract the type from the schema
// as Joi already knows what we expect the type to be
type schema = Joi.extractType<typeof schema>;

// schema type would look like the following
// schema: {
//   username: string;
//   password: string
// }

Do you have a new or modified API suggestion to solve the problem?

Joi extract type plugin has solved this in the past, but hasn't kept up with the latest releases of Joi, and it does feel reliable for a long term use. Can't that logic be part of the hapi/joi library instead?

AGrabovajFitA avatar Oct 14 '22 10:10 AGrabovajFitA