扩展.d.ts文件中定义的接口 [英] Extend interface defined in .d.ts file

查看:798
本文介绍了扩展.d.ts文件中定义的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的TypeScript项目中,我对外部js依赖项使用 DefinitelyTyped 定义。

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

有时,这些定义可能会过时。也可能会发生某些库在运行时添加新方法,例如 express-validator 可以定义自定义验证器函数。

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.

因此我想扩展那些 .d.ts 定义添加新方法和/或属性。

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

所以如果我在 express-validator.d.ts 中有我的DefinitelyTyped定义:

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

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

我该如何延期 Validator 界面,例如我的 application.ts

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


推荐答案


//如何扩展Validator接口添加isArray()方法??

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

不能在作为模块的文件中执行此操作此处的一些指导)您的文件是一个模块,因为您拥有 import expressValidator

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.

而是创建 extendedValidator.d.ts 并为TypeScript引擎添加新内容:

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

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

这篇关于扩展.d.ts文件中定义的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆