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

查看:78
本文介绍了.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 中有我的绝对类型定义:

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

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

如何在例如我的 application.ts 中扩展 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??

推荐答案

//如何扩展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天全站免登陆