| name | migrate-to-shoehorn |
| description | 将测试文件中的 `as` 类型断言迁移到 @total-typescript/shoehorn。适用于用户提到 shoehorn、希望替换测试中的 `as`,或需要构造不完整测试数据的场景。 |
迁移到 Shoehorn
为什么使用 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>;
};
it("gets user by id", () => {
getUser({
body: { id: "123" },
headers: {},
cookies: {},
});
});
迁移后:
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);
迁移后:
import { fromAny } from "@total-typescript/shoehorn";
getUser(fromAny({ body: { id: 123 } }));
各函数的适用场景
| 函数 | 适用场景 |
|---|
fromPartial() | 传入能够通过类型检查的部分数据 |
fromAny() | 传入故意错误的数据,同时保留自动补全 |
fromExact() | 强制提供完整对象,之后可替换为 fromPartial |
工作流程
- 收集要求——询问用户:
- 哪些测试文件中的
as 断言正在造成问题?
- 是否在处理只关心少数属性的大型对象?
- 是否需要在错误场景测试中传入故意错误的数据?
- 安装并迁移: