Ajv: Ajv.ValidationError type is not defined for TypeScript

Created on 20 Sep 2017  路  3Comments  路  Source: ajv-validator/ajv

What version of Ajv are you using? Does the issue happen if you use the latest version?
5.2.2, Yes

if ( err instanceof Ajv.ValidationError ) { ... }

Error I receive:

Property 'ValidationError' does not exist on type '{ (options?: Options | undefined): Ajv; new (options?: Options | undefined): Ajv; }'.

enhancement typescript

Most helpful comment

For some reason, it still reports Cannot use 'new' with an expression whose type lacks a call or construct signature. for ValidationError when I try new ValidationError(ajv.errors)

All 3 comments

There is also Ajv.MissingRefError

For some reason, it still reports Cannot use 'new' with an expression whose type lacks a call or construct signature. for ValidationError when I try new ValidationError(ajv.errors)

@epoberezkin as you declared https://github.com/epoberezkin/ajv/blob/28386786fd9f6229652829a673745a1563e097c7/lib/ajv.d.ts#L1-L7

You are declaring ValidationError field as an instance of the ValidationError class.

You can even do

import ajv from 'ajv';
console.log(ajv.ValidationError.ajv); // the docs say it's `true`, but it's actually `undefined`.

The correct way should be

ValidationError: typeof ValidationError;

This allows you to do new ajv.ValidationError.


But, it still doesn't allow you to declare a variable as ajv.ValidationError type, because the type itself is now exported.

const error: ajv.ValidationError; // nope

To resolve this, I found this strange way:

declare namespace Errors {
  class ValidationError extends Error { /* ... */ }

  class MissingRefError extends Error { /* ... */ }
}

declare var ajv: {
  (options?: ajv.Options): ajv.Ajv;
  new(options?: ajv.Options): ajv.Ajv;
  ValidationError: typeof Errors.ValidationError;
  MissingRefError: typeof Errors.MissingRefError;
  $dataMetaSchema: object;
}

declare namespace ajv {
  type ValidationError = Errors.ValidationError;

  type MissingRefError = Errors.MissingRefError;

  /* ... */
}

Now you can write:

import ajv from 'ajv';

const validationError: ajv.ValidationError = new ajv.ValidationError([]);
const missingRefError: ajv.MissingRefError = new ajv.MissingRefError("", "", "");
Was this page helpful?
0 / 5 - 0 ratings