在Typescript中向现有模块添加定义

时间:2017-09-18 09:38:53

标签: javascript node.js typescript node-modules

我正在努力使用Typescript并修改现有模块的定义。

我们习惯于将任何想要输出的内容输出到“res.out”,最后会出现类似“res.json(res.out)”的内容。这使我们可以在发送响应时对应用程序进行一般控制。

所以我有这样的功能

export async function register(req: Request, res: Response, next: Next) {
    try {
        const user = await userService.registerOrdinaryUser(req.body)
        res.status(201);
        res.out = user;
        return helper.resSend(req, res, next);
    } catch (ex) {
        return helper.resError(ex, req, res, next);
    }
};

我们正在使用解决方案。我得到编译错误,因为“out”不是restify.Response的一部分。

现在我们有了解决方法,我们拥有“自己的”对象,扩展了Restify对象。

import {
    Server as iServer,
    Request as iRequest,
    Response as iResponse,
} from 'restify'

export interface Server extends iServer {
}

export interface Request extends iRequest {
}

export interface Response extends iResponse {
    out?: any;
}

export {Next} from 'restify';

我们这样做是为了使项目可编译,但寻找更好的解决方案。我尝试过这样的事情:

/// <reference types="restify" />

namespace Response {
    export interface customResponse;
}

interface customResponse {
    out?: any;
}

但它不起作用,现在它说“重复标识符'响应'”。

那么有人如何用一些简单的代码为restify.Response对象添加定义?

1 个答案:

答案 0 :(得分:4)

您可以使用interface merging

import {  Response } from "restify";
declare module "restify" {
    interface Response {
        out?: any
    }
}