mcpField
M
migrate-to-shoehorn

migrate-to-shoehorn

github.com/tt-a1i测试与质量19296 次安装2 天前更新
代码仓库

关于 migrate-to-shoehorn

此迁移技能指导开发者用 `@total-typescript/shoehorn` 的辅助函数替换 TypeScript 测试中的类型断言。它说明如何处理部分数据、故意错误的数据和完整对象,仅适用于测试,不应在生产代码中使用。

主要功能

  1. 01用 `fromPartial()` 替换 `as Type`
  2. 02用 `fromAny()` 替换双重断言
  3. 03用 `fromExact()` 强制完整对象
  4. 04查找测试文件中的断言
  5. 05安装包并验证类型

适用场景

  1. 01迁移使用部分请求对象的测试
  2. 02编写包含故意无效数据的测试
  3. 03查找 `.test.ts` 和 `.spec.ts` 中的类型断言

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/tt-a1i/matt-skills-with-to-goal --skill migrate-to-shoehorn

安装后在 Claude Code 中输入/migrate-to-shoehorn确认已加载。

附带文件agents/openai.yaml

详细介绍

迁移到 Shoehorn

为什么使用 shoehorn?

shoehorn 让你在测试中传入部分数据,同时保持 TypeScript 类型检查通过。它用类型安全的替代方案取代 as 断言。

仅限测试代码。 切勿在生产代码中使用 shoehorn。

在测试中使用 as 的问题:

  • 已养成避免使用它的习惯
  • 必须手动指定目标类型
  • 为故意传入错误数据而需要双重 as(as unknown as Type)

安装

npm i @total-typescript/shoehorn

迁移模式

大对象但只需少量属性

迁移前:

type Request = {
  body: { id: string };
  headers: Record<string, string>;
  cookies: Record<string, string>;
  // ...20 more properties
};

it("gets user by id", () => {
  // Only care about body.id but must fake entire Request
  getUser({
    body: { id: "123" },
    headers: {},
    cookies: {},
    // ...fake all 20 properties
  });
});

迁移后:

import { fromPartial } from "@total-typescript/shoehorn";

it("gets user by id", () => {
  getUser(
    fromPartial({
      body: { id: "123" },
    }),
  );
});
as Type → fromPartial()

迁移前:

getUser({ body: { id: "123" } } as Request);

迁移后:

import { fromPartial } from "@total-typescript/shoehorn";

getUser(fromPartial({ body: { id: "123" } }));
as unknown as Type → fromAny()

迁移前:

getUser({ body: { id: 123 } } as unknown as Request); // wrong type on purpose

迁移后:

import { fromAny } from "@total-typescript/shoehorn";

getUser(fromAny({ body: { id: 123 } }));

各函数的使用场景

函数使用场景
fromPartial()传入仍能通过类型检查的部分数据
fromAny()传入故意错误的数据(保留自动补全)
fromExact()强制使用完整对象(之后可与 fromPartial 互换)

工作流程

  1. 收集需求 - 询问用户:

    • 哪些测试文件中的 as 断言引发了问题?
    • 它们是否处理只有部分属性有用的大对象?
    • 是否需要为错误测试传入故意错误的数据?
  2. 安装并迁移:

    • 安装:npm i @total-typescript/shoehorn
    • 查找带有 as 断言的测试文件:grep -r " as [A-Z]" --include="*.test.ts" --include="*.spec.ts"
    • 将 as Type 替换为 fromPartial()
    • 将 as unknown as Type 替换为 fromAny()
    • 添加来自 @total-typescript/shoehorn 的导入
    • 运行类型检查以验证

评论

支持 Markdown