在Typescript中向现有模块添加定义 [英] Add definition to existing module in Typescript

查看:165
本文介绍了在Typescript中向现有模块添加定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am struggling with Typescript and modifying the definition of existing module.

我们习惯将任何想要输出的内容放到res.out和结束有这样的事情res.json(res.out)。这允许我们在发送回复时对应用程序进行一般控制。

We are used to put anything we want to output to "res.out" and at the end there is something like this "res.json(res.out)". This allows us to have general control over the app at the moment of sending the response.

所以我有这样的功能

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的一部分。

We are using restify. And I get compilation error, because "out" is not part of restify.Response.

现在我们有了解决办法,我们拥有自己的对象,这扩展了Restify那些。

Now we have workaround that we have our "own" objects, that extends the Restify ones.

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';

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

We just did this to make project compilable, but looking for better solution. I have tried things like this:

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

namespace Response {
    export interface customResponse;
}

interface customResponse {
    out?: any;
}

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

But it does not work, right now it says "Duplicate identifier 'Response'".

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

So anyone how to add definition to restify.Response object with some simple code?

推荐答案

您可以使用界面合并

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

这篇关于在Typescript中向现有模块添加定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆