您无法删除在类型上定义的函数,我们可以为该类型添加一个重载json
带有模块增强的函数,但这没什么用处,因为如果我们弄错了属性,编译器将选择允许任何属性的函数的原始版本。
更激进的方法是创建一种与Response
但这会删除原来的json
方法并将其替换为类型化版本。我们可以使用映射类型,这样我们就不会重复任何原始类型:
// Helpers
type Diff<T extends string, U extends string> = ({ [P in T]: P } & { [P in U]: never } & { [x: string]: never })[T];
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;
// Generic typed response, we omit 'json' and we add a new json method with the desired parameter type
type TypedResponse<T> = Omit<Response, 'json'> & { json(data: T): Response };
// An example of a typed response
type AppResponse = TypedResponse<{
success: boolean,
data?: any,
error?: string,
}>
app.get('/', async (req: Request, res: AppResponse, next: NextFunction) => {
try {
// ....
} catch (error) {
return res.json({
success: false,
error: error.message,
errors: "" // causses error
});
}
return res.json({
success: true,
data: {
message: 'Account registered',
},
});
}
不幸的是,没有办法强制开发人员使用通用版本(除了长棍),但通过代码审查,这可能对您来说足够有效。