扩展打字稿界面 [英] Extending typescript interface
问题描述
在TypeScript中扩展Express.Request接口时,我遇到了我想使用外部库定义的问题,但是由于导致错误->
When extending the Express.Request interface in TypeScript I ran into this problem that I want to use an external library definition, but I can't import the external library as it results in error ->
错误:(4,28)TS1147:内部模块中的导入声明无法引用外部模块.
Error:(4, 28) TS1147: Import declarations in an internal module cannot reference an external module.
这是一个.d.ts文件
It is a .d.ts file
/// <reference path="../typings/express/express.d.ts" />
declare module Express {
import bunyan = require('bunyan'); <-- results in error
export interface Request {
_id: string; <-- this works
log: bunyan.Logger; <-- Here I want to define that it is bunyan.Logger instance;
}
}
尝试引用bunyan.d.ts( https: //github.com/borisyankov/DefinitelyTyped/blob/master/bunyan/bunyan.d.ts ) 由于将bunyan模块导出为字符串,因此也会导致问题
Trying to reference the bunyan.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/bunyan/bunyan.d.ts) Also results in a problem, as the bunyan module is exported as string
declare module "bunyan" {
...
}
如此一来,试图从参考中使用它就找不到了.
As such trying to use it from reference results in not found.
/// <reference path="../typings/express/express.d.ts" />
/// <reference path="../typings/bunyan/bunyan.d.ts" />
declare module Express {
export interface Request {
_id: string;
log: bunyan.Logger; <- Error:(8, 18) TS2304: Cannot find name 'bunyan'.
}
}
tl; dr;如何使用外部模块定义扩展接口定义.
tl;dr; How to extend interface definition with external module definitions.
推荐答案
我不认为您可以在需要require
时添加到现有接口,但是可以使用extends
关键字扩展现有接口
I don't think you can add to an existing interface when a require
is necessary, but you can extend the existing interface using the extends
keyword.
将import语句移至模块之外,导出模块,并扩展现有接口:
Move your import statement outside your module, export your module, and extend the existing interface:
import bunyan = require('bunyan');
import express = require('express');
export declare module ExtendedExpress {
export interface Request extends express.Express.Request {
_id: string;
log: bunyan.Logger;
}
}
然后,您必须将模块导入到要使用的位置.
Then you have to import this module where you want to use it.
这篇关于扩展打字稿界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!