簡體   English   中英

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

我們正在使用解決方案。 我得到編譯錯誤,因為“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對象添加定義?

您可以使用界面合並

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM