cta*_*ppy 3 node.js express type-declaration typescript
在打字稿中,我试图将 Express 的Response
json
对象覆盖为始终使用的特定类型的对象
例如,我想强制执行一种接口类型,如果不遵循以下格式,该接口类型就会出错
return res.status(200).json({
data: ["a", {"a": "b"}],
success: true,
});
Run Code Online (Sandbox Code Playgroud)
我尝试使用dts-gen --m express -f src/types/express.d.ts
创建声明文件进行修改,但以失败告终。
有没有办法覆盖现有库上的特定类型,或者我是否需要创建特定于我的需求的声明文件?
interface Json {
success: boolean;
data: any[];
}
type Send<T = Response> = (body?: Json) => T;
interface CustomResponse extends Response {
json: Send<this>;
}
Run Code Online (Sandbox Code Playgroud)
我能够创建一个新的界面来扩展它。只需要多了解一点:)希望这可以帮助其他人!
您可以在req
和res
对象的通用类型中设置自定义类型,例如:
import type * as E from 'express';
interface CustomResponseType {
test: string;
}
export default async function Example(
req: E.Request<undefined, CustomResponseType, [CustomReqBodyType?], [CustomReqQueryType?]>,
res: E.Response<CustomResponseType>
): Promise<E.Response<CustomResponseType, Record<string, any>>> {
return res.status(200).json({ test: 'success' });
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9930 次 |
最近记录: |