Skip to content

question: is there a way to ensure validators and types match? #1951

Open
@nicolaschambrier

Description

@nicolaschambrier

We're comparing different schema validation libraries and one of my strongest concerns is the possibility to lie with class-validator. Here is an obviously stupid example, but it shows how we can have validators that make zero sense with the type, but will still wait for runtime to fail:

class TestClass {
  @IsOptional()
  @IsString()
  age: number

  @IsBoolean()
  lastName?: string

  @IsBoolean()
  firstName?: string
}

const tstObj1 = new TestClass()
tstObj1.age = 42
tstObj1.firstName = undefined
tstObj1.lastName = 'test'

expect(validateSync(tstObj1)).toEqual([
  {
    target: tstObj1,
    value: 42,
    property: 'age',
    children: [],
    constraints: { isString: 'age must be a string' },
  },
  {
    target: tstObj1,
    value: 'test',
    property: 'lastName',
    children: [],
    constraints: { isBoolean: 'lastName must be a boolean value' },
  },
  {
    target: tstObj1,
    value: undefined,
    property: 'firstName',
    children: [],
    constraints: { isBoolean: 'firstName must be a boolean value' },
  },
])

In "real life" this happened with @IsOptional() which had been added where it should have not, and was not here where it should have. But I guess in bigger models it can happen on more sever cases.

How can I ensure the validators and the types always match, at least for the basics?

What I expected here

Typing errors preventing compilation:

  • Cannot use @IsOptional() @IsString() on "age" as string | null | undefined is not compatible with number
  • Cannot use @IsBoolean() on "lastName" as boolean is not compatible with string | undefined
  • Cannot use @IsBoolean() on "firstName" as boolean is not compatible with string | undefined

Maybe it's just a limitation of the decorators, I still hope it can be achieved with strictier typing on validators.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questionQuestions about the usage of the library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions