在 TypeScript 中扩展 Express.Request 接口(interface)时遇到了这个问题,我想使用外部库定义,但我无法导入外部库,因为它会导致错误 ->
错误:(4, 28) TS1147:内部模块中的导入声明不能引用外部模块。
编辑:这是一个.d.ts文件
/// <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 模块导出为字符串
declare module "bunyan" {
...
}
因此尝试从引用结果中使用它未找到。
/// <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;博士;如何使用外部模块定义扩展接口(interface)定义。
最佳答案
我认为当 require
是必需的时,您不能添加到现有接口(interface),但您可以使用 extends
关键字扩展现有接口(interface)。
将导入语句移到模块外,导出模块并扩展现有接口(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;
}
}
然后你必须在你想使用它的地方导入这个模块。
关于interface - 扩展 typescript 界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29516522/