Search code examples
typescriptvalidationjoi

how to properly construct a Joi validation for a field returning a function


I'm trying to building Joi schema validation for:

type Toy = {
id: string;
codeName: (nameFormat?: string) => string;
price: number;
}

The problem is with the validation of codeName. I don't know how to represent that the codeName is a function with an optional parameter (type string) that returns a string. And the codeName field is actually a required field

I tried to work out a solution with documentation - no grater result I didn't found any convergent topics on Stack Overflow and other

My project is using Joi in ver 14 I will be grateful for your help

And What I trying to build when I speak about schema: For Example

type CarSchema = {
mark: Joi.string().required(),
color: Joi.string().required(),
price: Joi.number().required(),
accessories: Joi.string().optional(),
}

Solution

  • Best you can do is:

    export const toySchema = Joi.object({
      id: Joi.string(),
      codeName: Joi.func().minArity(0).maxArity(1),
      price: Joi.number(),
    });
    

    Since JavaScript has no notion of type, and TypeScript does not provide RTTI, there's no way for you to check either the types of the expected arguments of a function, or the return type.