当前位置: 动力学知识库 > 问答 > 编程问答 >

typescript - Extend interface defined in .d.ts file

问题描述:

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??

网友答案:

// 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;
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: