Extend interface defined in .d.ts file

蹲街弑〆低调 提交于 2019-12-28 03:01:27

问题


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

回答1:


// 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;
  }
}



回答2:


I was able to accomplish this by following the directions at https://www.credera.com/blog/technology-solutions/typescript-adding-custom-type-definitions-for-existing-libraries/. There they use the example of react.

import 'react';

declare module 'react' {
    interface OlHTMLAttributes<T> {
        type?: "1" | "a" | "A" | "i" | "I";
    }
}```

I found this works really well for `winston` too.


来源:https://stackoverflow.com/questions/32948271/extend-interface-defined-in-d-ts-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!