返回技能市场
开发运维 安全

migrate-to-shoehorn

@admin/migrate-to-shoehorn

Migrate test files from `as` type assertions to @total-typescript/shoehorn. Use when user mentions shoehorn, wants to replace `as` in tests, or needs partial test data.

admin 热度 315v0.0.1

迁移到 Shoehorn

为什么使用 shoehorn?

shoehorn 允许你在测试中传递部分数据,同时让 TypeScript 保持满意。它用类型安全的替代方案替换 as 断言。

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

测试中使用 as 的问题:

  • 被训练为不使用它
  • 必须手动指定目标类型
  • 对于故意错误的数据需要双重 asas 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 TypefromPartial()

之前:

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

之后:

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

getUser(fromPartial({ body: { id: "123" } }));

as unknown as TypefromAny()

之前:

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 断言?
  • 他们是否处理大型对象,其中只有某些属性重要?
  • 他们是否需要传递故意错误的数据以进行错误测试?
  1. 安装并迁移
  • [ ] 安装: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 的导入
  • [ ] 运行类型检查以验证
qianwen skills install @admin/migrate-to-shoehorn