Skip to content

Incompatible type expected for object schemas nested in strict object schemas #2764

@bryandrenner

Description

@bryandrenner

Context

  • node version: 14.19.1
  • module version with issue: 17.5.0, 17.6.0
  • last module version without issue: 17.4.3
  • environment (e.g. node, browser, native): Node
  • used with (e.g. hapi application, another framework, standalone, ...): standalone

What are you trying to achieve or the steps to reproduce?

When I nest an object schema inside of another, strict object schema, I expect no type issues. For example, the following code compiles in v17.4.3:

import Joi from 'joi'

type Name = {
    first: string
    last: string
}

const nameSchema = Joi.object<Name>({
    first: Joi.string().required(),
    last: Joi.string().required()
})

type Customer = {
    name: Name
}

const customerSchema = Joi.object<Customer, true>({
    name: nameSchema
})

What was the result you got?

As of v17.5.0, the above code does not compile. The compiler reports the following:

demo.ts:18:5 - error TS2322: Type 'ObjectSchema<Name>' is not assignable to type 'ObjectSchema<StrictSchemaMap<Name>>'.
  Types of property 'concat' are incompatible.
    Type '(schema: ObjectSchema<Name>) => ObjectSchema<Name>' is not assignable to type '(schema: ObjectSchema<StrictSchemaMap<Name>>) => ObjectSchema<StrictSchemaMap<Name>>'.
      Types of parameters 'schema' and 'schema' are incompatible.
        Type 'ObjectSchema<StrictSchemaMap<Name>>' is not assignable to type 'ObjectSchema<Name>'.
          The types returned by 'validate(...)' are incompatible between these types.
            Type 'ValidationResult<StrictSchemaMap<Name>>' is not assignable to type 'ValidationResult<Name>'.
              Type '{ error: undefined; warning?: ValidationError | undefined; value: StrictSchemaMap<Name>; }' is not assignable to type 'ValidationResult<Name>'.
                Type '{ error: undefined; warning?: ValidationError | undefined; value: StrictSchemaMap<Name>; }' is not assignable to type '{ error: undefined; warning?: ValidationError | undefined; value: Name; }'.
                  Types of property 'value' are incompatible.
                    Type 'StrictSchemaMap<Name>' is not assignable to type 'Name'.

18     name: nameSchema

What result did you expect?

I would expect the code to compile without issues.

If I change this line:

const customerSchema = Joi.object<Customer, true>({

...to this:

const customerSchema = Joi.object<Customer>({

...then the code compiles, but I lose the safety of strict object schemas.

Metadata

Metadata

Assignees

Labels

bugBug or defecttypesTypeScript type definitions

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions