用途
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 的导入
- 运行类型检查以验证
适用场景
- 测试文件中存在大量
as类型断言 - 测试需要构造大型对象但只关心其中少量属性
- 需要为错误测试传入故意错误的数据
限制
- 仅用于测试代码,禁止在生产代码中使用
- 需要安装 @total-typescript/shoehorn 依赖
- 迁移后需运行类型检查验证