hapijs / joi

The most powerful data validation library for JS
Other
20.95k stars 1.51k forks source link

Add support for Typescript's exactOptionalPropertyTypes setting #2943

Open billy-onerail opened 1 year ago

billy-onerail commented 1 year ago

Support plan

Context

What problem are you trying to solve?

We are using a stricter typescript config with exactOptionalPropertyTypes set as true, and we get TS errors when defining what an array of items can be.

import Joi from 'joi';
import { array } from 'joiful';

@array()
        .items(
            Joi.string().guid({
                version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'],
            }),
            Joi.number(),
            Joi.object()
        )
        .required()
identifier!: (string | number | JSONObject)[];

Causes this typescript error:

error TS2379: Argument of type 'StringSchema<string>' is not assignable to parameter of type 'Schema' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
  Type 'StringSchema<string>' is not assignable to type 'StringSchema' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
    Types of property 'alter' are incompatible.
      Type '(targets: Record<string, (schema: StringSchema<string>) => Schema<any>>) => StringSchema<string>' is not assignable to type '(targets: Record<string, SchemaFunction>) => StringSchema'.
        Types of parameters 'targets' and 'targets' are incompatible.
          Type 'Record<string, SchemaFunction>' is not assignable to type 'Record<string, (schema: StringSchema<string>) => Schema<any>>'.
            'string' index signatures are incompatible.
              Type 'SchemaFunction' is not assignable to type '(schema: StringSchema<string>) => Schema<any>'.

200             Joi.string().guid({
                ~~~~~~~~~~~~~~~~~~~
201                 version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'],
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
202             }),
    ~~~~~~~~~~~~~~

To get around this error we have to use any which is not ideal, and also tell the linter to stop warning us about the use of any:

@array()
        .items(
            Joi.string().guid({
                version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'],
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
            }) as any,
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            Joi.number() as any,
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            Joi.object() as any
        )
        .required()

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

Updating the joi optional types to include undefined per the TS documentation would solve the issue and add support for that setting.