4

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 Answer 1

5

You can use interface merging.

import {  Response } from "restify";
declare module "restify" {
    interface Response {
        out?: any
    }
}    
Sign up to request clarification or add additional context in comments.

3 Comments

I have tried and it completely "delete" the original 'restify' and put this in its position, therefore now the only things that typescript knows is Response.out
@libik You need to import the original interface you want to extend. See the updated answer.
Importing the original interface makes this augmentation file inactive for some reasons

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.