You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 01:10:00