我正在努力使用 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的一部分。
现在我们有了解决方法,我们拥有“自己的”对象,可以扩展 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 对象添加定义?