interface - 扩展 typescript 界面

标签 interface typescript

在 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/

相关文章:

c# - 通过接口(interface)在多个集合中引用同一个对象

javascript - Angular2 数据表的搜索/过滤组件

javascript - Angular 4 为每个环境创建 Assets /文件?

c# - 接口(interface)的好案例

Java 面向对象编程多个类实例

java - 如何将实现特定接口(interface)的任何类作为参数传递并使用其方法?

C# 转换问题 : from IEnumerable to custom type

javascript - typescript 中的功能

Angular 5 : how to refer to a subcomponent method from a parent component HTML template?

javascript - 如何使用在单击按钮上创建的用户触发放大和缩小绘图图表?