Add definition to existing module in Typescript

一笑奈何 提交于 2019-12-20 02:36:11

问题


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

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.

So I have function like this

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);
    }
};

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

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'".

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


回答1:


You can use interface merging.

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


来源:https://stackoverflow.com/questions/46276117/add-definition-to-existing-module-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!