如何基于另一变量值为TypeScript变量分配对应类型?
实现TypeScript中基于this属性值的参数类型自动推导
你可以通过泛型+类型映射表的方式实现需求,无需依赖函数重载,具体步骤如下:
1. 定义类型映射关系
先创建一个类型别名,把document的字符串值和对应的数据类型做绑定:
// 假设已提前定义Post、User、Comment类型 type DocumentTypeMap = { post: Post; user: User; comment: Comment; };
2. 改造DocumentObject为泛型接口
让DocumentObject带上泛型参数,约束为DocumentTypeMap的键类型,同时关联insert方法的参数类型:
interface DocumentObject<T extends keyof DocumentTypeMap> { document: T; insert: (this: DocumentObject<T>, record: DocumentTypeMap[T]) => Promise<void>; }
3. 实现document()泛型函数
让document()函数接收泛型参数,返回对应类型的DocumentObject实例:
function document<T extends keyof DocumentTypeMap>(docType: T): DocumentObject<T> { return { document: docType, async insert(record) { // 这里可通过this.document获取当前文档类型,执行插入逻辑 console.log(`插入${this.document}类型数据:`, record); } }; }
4. 验证效果
此时调用document("post").insert(...)时,TypeScript会自动推导record必须是Post类型,同理传入user或comment时会对应User/Comment类型:
// 自动推导record为Post类型 document("post").insert({ id: 1, title: "TypeScript技巧" }); // 自动推导record为User类型 document("user").insert({ id: 2, username: "test" });
这种方式的优势在于:
- 无需维护大量函数重载,扩展性强,新增文档类型只需在
DocumentTypeMap中添加对应条目 - 类型推导完全基于泛型约束,逻辑清晰,符合TypeScript的类型系统设计
内容的提问来源于stack exchange,提问作者Omar Ahmed
相关产品推荐
相关产品推荐

