Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

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??
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...