Ajv: Module can't be used in typescript

Created on 5 Apr 2019  路  6Comments  路  Source: ajv-validator/ajv

I am missing examples how to use this module in typescript. The usual typescript patterns do not work. ajv.d.ts does not make much sense, it cannot be used to import anything useful (executable functions or objects) into a typescript program.
Could you please show some working example?

usage

Most helpful comment

So I was finally able to nail down the syntax I needed. Using import Ajv from 'ajv'; works to import the namespace and class, however import * as Ajv from 'ajv'; and import { Ajv } from 'ajv'; do not. Sorry for the confusion.

All 6 comments

@radio-miskovice please see the usage in any dependant library / codebase or please submit the question to StackOverflow

Having a bit of a problem here as well. I'm able to import is like so import * as Ajv from 'ajv' and everything seems to resolve, however when I go to compile, the compiler throws error "Cannot use 'new' with an expression whose type lacks a call or construct signature" when trying to instantiate a new AJV instance.

Looks like the new --esModuleInterop flag in Typescript compiler prevents the import of AJV. Previously, you able to simply import like so import * as Ajv from 'ajv' but, with Typescript 2.7+, when turning on esModuleInterop, you get an error. This is intended per the docs. Looks like the type definition needs to be updated?

So I was finally able to nail down the syntax I needed. Using import Ajv from 'ajv'; works to import the namespace and class, however import * as Ajv from 'ajv'; and import { Ajv } from 'ajv'; do not. Sorry for the confusion.

Are the type definitions correct, though?
When importing import Ajv from "ajv"; and trying to use Ajv as a type you'll get Cannot use namespace 'Ajv' as a type. from tsc.
You could import { Ajv } from "ajv"; - that would fix the tsc issue, but the module doesn't actually export it, so in runtime it won't work.
Am I missing something?

Looks like you can do

import Ajv from 'ajv';

with :

// tsconfig.json
"allowSyntheticDefaultImports": true,
Was this page helpful?
0 / 5 - 0 ratings