typescript .d.ts 文件中定义的扩展接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32948271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extend interface defined in .d.ts file
提问by Marco Ancona
In my TypeScript project, I use DefinitelyTypeddefinitions for external js dependencies.
在我的 TypeScript 项目中,我对外部 js 依赖项使用了绝对类型定义。
Sometimes it might happen that these definitions are outdated. It might also happen than some libraries can add new methods at runtime, like express-validatorin which you can define custom validator functions.
有时可能会发生这些定义已经过时的情况。这也可能发生在某些库可以在运行时添加新方法时,例如express-validator,您可以在其中定义自定义验证器函数。
Therefore I would like to extend those .d.ts
definitions adding new methods and/or properties.
因此,我想扩展这些.d.ts
定义,添加新的方法和/或属性。
So if I have my DefinitelyTyped defininiton in express-validator.d.ts
:
所以如果我有我的绝对类型定义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
?
我如何扩展Validator
接口,例如,我的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??
采纳答案by basarat
// How to extend Validator interface adding isArray() method??
// 如何扩展 Validator 接口添加 isArray() 方法?
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
.
您不能在作为模块的文件中执行此操作(此处提供一些指导)并且您的文件是一个模块,因为您有import expressValidator
.
Instead create a extendedValidator.d.ts
and add the new stuff for TypeScript's engine:
而是extendedValidator.d.ts
为 TypeScript 的引擎创建一个并添加新内容:
declare module ExpressValidator {
export interface Validator {
isArray: any;
}
}
回答by cjbarth
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
.
我能够按照https://www.credera.com/blog/technology-solutions/typescript-adding-custom-type-definitions-for-existing-libraries/上的说明完成此操作。在那里他们使用react
.
import 'react';
declare module 'react' {
interface OlHTMLAttributes<T> {
type?: "1" | "a" | "A" | "i" | "I";
}
}```
I found this works really well for `winston` too.