Extend interface defined in .d.ts file

Marco Ancona picture Marco Ancona · Oct 5, 2015 · Viewed 22.4k times · Source

In my TypeScript project, I use DefinitelyTyped definitions for external js dependencies.

Sometimes it might happen that these definitions are outdated. It might also happen than some libraries can add new methods at runtime, like express-validator in which you can define custom validator functions.

Therefore I would like to extend those .d.ts definitions adding new methods and/or properties.

So if I have my DefinitelyTyped defininiton in express-validator.d.ts:

declare module ExpressValidator {
  export interface Validator {
    is(): Validator;
    not(): Validator;
    isEmail(): Validator;
    ...
  }
}

how can I extend Validator interface within, for example, my application.ts ?

///<reference path='../typings/tsd.d.ts' />

import expressValidator = require('express-validator');
export var app = express();

app.use(expressValidator({
    customValidators: {
        isArray: function(value) {
            return Array.isArray(value);
        }
 }
}));

// How to extend Validator interface adding isArray() method??

Answer

basarat picture basarat · Oct 6, 2015

// How to extend Validator interface adding isArray() method??

You cannot do this in a file that is a module (some guidance here) and your file is a module because you have import expressValidator.

Instead create a extendedValidator.d.ts and add the new stuff for TypeScript's engine:

declare module ExpressValidator {
  export interface Validator {
     isArray: any;
  }
}