React TypeScript测试用例用Mock数据遇TS2345类型错误
React TypeScript测试中MSW Mock数据的类型错误解决
问题说明
在React TypeScript测试用例中使用MSW(mock service worker)模拟接口数据时,出现TypeScript类型错误:
TS2345: 类型'(req: any, res: any, ctx: any) => any'无法赋值给类型'HttpResponseResolver<PathParams, DefaultBodyType, undefined>'。
测试用例代码如下:
import { http } from 'msw'; export const handlers = [ http.get("https://jsonplaceholder.typicode.com/users", (req, res, ctx) => { return res( ctx.status(200), ctx.json([ { name: 'Leanne Graham' }, { name: 'Ervin Howell' }, { name: 'Clementine Bauch' }, ]) ) }) ];
解决方法
1. 移除any类型,依赖自动类型推导
MSW的http.get回调参数自带内置类型,无需手动指定any,直接省略类型声明即可让TypeScript自动推导正确的参数类型:
import { http } from 'msw'; export const handlers = [ http.get("https://jsonplaceholder.typicode.com/users", (req, res, ctx) => { return res( ctx.status(200), ctx.json([ { name: 'Leanne Graham' }, { name: 'Ervin Howell' }, { name: 'Clementine Bauch' }, ]) ) }) ];
2. 显式指定类型(可选)
如果需要更严谨的类型约束,可以自定义数据类型并显式声明:
import { http, PathParams } from 'msw'; // 定义返回数据的类型 type User = { name: string; }; export const handlers = [ // 显式指定路径参数类型和响应体类型 http.get<PathParams, User[]>("https://jsonplaceholder.typicode.com/users", (req, res, ctx) => { return res( ctx.status(200), ctx.json([ { name: 'Leanne Graham' }, { name: 'Ervin Howell' }, { name: 'Clementine Bauch' }, ]) ) }) ];
3. 检查MSW版本
若上述方法无效,确认MSW是否为最新稳定版,旧版本可能存在类型定义兼容问题,执行更新命令:
npm update msw # 或使用yarn yarn upgrade msw
内容的提问来源于stack exchange,提问作者Pradeep
相关产品推荐
相关产品推荐

