Skip to content

Type level validation of schema #2622

@BackEndTea

Description

@BackEndTea

Support plan

  • is this issue currently blocking your project? no
  • is this issue affecting a production system? no

Context

  • node version: 14
  • module version: 17.4
  • environment node
  • used with standalone
  • any other relevant information: N/A

What problem are you trying to solve?

We're using Joi to validate a bunch of input. I want to make sure that every property is validated, as present, and the correct type.

For example i may have the following type, and its validation:

interface User {
  id: number,
  name: string
}

Joi.object<User>({
  id: Joi.number()
});

here i forgot to add validation for the name. Prehaps it was added later, and validation was forgotten. I'd like to have typescript errors when this happends

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

This is currently my homebrewn solution. One of the problems here is that i can't validate the generic types of Array, or if i use alternatives. ( If our object is of type Record<any, any> it can also be an empty array, which is why we use AlternativesSchema)

type StateSchema<T = object> = {
    [key in keyof T]: T[key] extends string
        ? StringSchema
        : T[key] extends number
        ? NumberSchema
        : T[key] extends boolean
        ? BooleanSchema
        : T[key] extends Array<any>
        ? ArraySchema
        : T[key] extends object
        ? ObjectSchema<T[key]>|AlternativesSchema
        : never
    ;
};

export const joiObject = <T>(input: StateSchema<T>): ObjectSchema<T> => Joi.object<T>(input);

Metadata

Metadata

Assignees

Labels

typesTypeScript type definitions

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions