6
votes

I'm trying to use the validate.js library, which includes its own TypeScript declaration file.

Unfortunately it's not a very good typing of the library, and there's a much better one in DefinitelyTyped. I installed the @types/validate.js NPM package, but TypeScript isn't using it, and is instead using the declarations bundled directly with the library.

Is there any way to make the compiler use the better declarations I have available?

1

1 Answers

7
votes

You can't use declarations for validate.js from DefinitelyTyped alone because there is not a single top-level export in it - they just declare some interfaces inside ValidateJS namespace.

And you can't use bundled declarations for validate.js, at least for node (module=commonjs), because they use default export instead of export =.

So you have to provide your own declarations in order to import validate.js properly:

create file validate.d.ts:

declare var validate: (attributes: any, constraints: any, options?: any) => any;
export = validate;

And tell typescript to use it instead of the one in node_modules using paths in tsconfig.json:

  "compilerOptions": {
    "baseUrl": ".", // This must be specified if "paths" is.
    "paths": {
      "validate.js":  ["./validate.d.ts"]
    }
  }

(Note that you must have baseUrl if you have paths, so set "baseUrl" : "." if you don't have it set to something else already)

Then you can use it like this (ValidateJS.Constraints and others are available immediately as soon as you npm install @types/validate.js):

import validate = require('validate.js');


let constraints: ValidateJS.Constraints = {
    'foo': {presence: true}
};

let e = validate({}, constraints);

console.dir(e);

output:

{ foo: [ 'Foo can\'t be blank' ] }