When it comes to using declarations for validate.js
from DefinitelyTyped, it's essential to note that relying solely on them is not sufficient. This is because there is no single top-level export
in the declarations - they simply declare some interfaces within the ValidateJS
namespace.
Furthermore, if you are working with bundled declarations for validate.js
, especially in a node environment (module=commonjs
), you will encounter issues due to the use of default exports instead of export =
.
As a solution, it becomes necessary to create your own declarations to correctly import validate.js
:
Create a file called validate.d.ts:
declare var validate: (attributes: any, constraints: any, options?: any) => any;
export = validate;
Instruct TypeScript to use this custom declaration file instead of the one in the node_modules
directory by utilizing paths in your tsconfig.json
file:
"compilerOptions": {
"baseUrl": ".", // Ensure to specify this if using "paths".
"paths": {
"validate.js": ["./validate.d.ts"]
}
}
(Note: If you are employing paths
, it is mandatory to have baseUrl
set. If it's not already set, define it as "baseUrl" : "."
)
Subsequently, you can use the imported declaration like this (note that ValidateJS.Constraints
and others become available once 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);
Result:
{ foo: [ 'Foo can\'t be blank' ] }