SuperAPI AI 工具集

migrate-to-shoehorn

测试与质量

查看项目

更新于 10-16 03:57

技能介绍

用途

migrate-to-shoehorn 用于将测试文件中的 as 类型断言迁移到 @total-typescript/shoehorn。适用场景:当用户提到 shoehorn、想要替换测试中的 as,或需要部分数据时使用。

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

使用限制

仅用于测试代码。绝不要在生产代码中使用 shoehorn。

测试中 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)

工作流

收集需求

询问用户:

  • 哪些测试文件中的 as 断言造成了问题?
  • 它们处理的是否是只需部分属性的大对象?
  • 是否需要为错误测试传入故意写错的数据?

安装并迁移

  • 安装: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 添加导入
  • 运行类型检查以验证

暂未提供的信息

关于该技能的收费、价格、支持的平台、实际效果等资料暂未提供。