第38章 ReturnType工具类型
案例38:ReturnType工具类型——提取函数返回类型
题目:设计一个函数,其返回值类型是一个复杂的对象。我们希望在类型层面自动提取该函数的返回类型,并基于它创建新类型(例如:部分可选、只读映射),而不需要手动重复声明该对象结构。
设计思路
TypeScript内置工具类型ReturnType<T>可以从函数类型中提取返回类型。本案例定义createUser函数,返回User对象。通过ReturnType<typeof createUser>获取返回类型,再结合Partial和Readonly工具类型生成新类型,演示类型提取与组合的实用场景。
核心代码
interface User {
id: number;
name: string;
email: string;
permissions: string[];
}
function createUser(id: number): User {
return {
id,
name: "张三",
email: "zhangsan@example.com",
permissions: ["read", "write"],
};
}
// 提取返回类型
type UserType = ReturnType<typeof createUser>;
// 基于提取的类型创建部分可选版本
type PartialUser = Partial<UserType>;
// 创建只读版本
type ReadonlyUser = Readonly<UserType>;
// 验证:声明变量
const updateData: PartialUser = { name: "李四" };
const frozenUser: ReadonlyUser = { id: 1, name: "王五", email: "w@ex.com", permissions: [] };
// 编译期验证(运行时不执行)
let check: UserType = createUser(1);
运行验证:在终端执行 npx tsc --strict --noEmit return-type-case.ts,若无报错则类型提取成功。也可用 ts-node 直接运行查看输出。
运行结果
本案例不产生运行时输出,核心价值在编译期类型检查。若添加以下代码,可打印对象验证:
console.log(updateData); // { name: "李四" }
console.log(frozenUser.id); // 1
成功要点:ReturnType只能用于函数类型,不能直接用于函数值,必须加typeof。提取后可自由组合其他工具类型,实现类型复用。
注意事项:ReturnType对重载函数只会提取最后一个重载的返回类型;对于泛型函数,提取结果是泛型参数被替换为unknown后的类型。
测试建议:尝试给createUser添加重载,验证ReturnType的行为;或尝试从async函数提取返回类型(会得到Promise<T>而非T)。