将定义添加到 Typescript 中的现有模块

Add definition to existing module in Typescript

我正在努力使用 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);
    }
};

我们正在使用 restify。我得到编译错误,因为 "out" 不是 restify.Response.

的一部分

现在我们有了 "own" 对象的解决方法,它扩展了 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;
}

但是它不起作用,现在显示 "Duplicate identifier 'Response'"。

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

您可以使用 interface merging.

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