TypeScript 如何基于带泛型的已有接口提取内部类型生成新接口
实现方案
你可以通过 TypeScript 的条件类型+infer 泛型提取配合映射类型实现,无需手动重写接口:
步骤1:定义泛型提取工具类型
首先用 infer 提取 StateVariable 尖括号内的泛型参数:
// 从 StateVariable<T> 中提取出 T 类型 type UnwrapStateVariable<T> = T extends StateVariable<infer U> ? U : never;
步骤2:批量解包原接口的所有属性
通过映射类型遍历原ImportAccountsState的所有属性,逐个解包:
// 通用的批量解包工具类型,可复用在所有被 StateVariable 包装的接口上 type UnwrapStateObject<T extends Record<string, StateVariable<any>>> = { [K in keyof T]: UnwrapStateVariable<T[K]> } // 直接生成你需要的目标类型 type UnwrappedImportAccountsState = UnwrapStateObject<ImportAccountsState>
效果验证
最终得到的UnwrappedImportAccountsState类型和你预期的完全一致:
// 等价于: // interface UnwrappedImportAccountsState { // isDialogOpen: boolean; // organization: string; // isOrganizationValid: boolean; // }
如果不需要复用解包逻辑,也可以直接写单行版本:
type UnwrappedImportAccountsState = { [K in keyof ImportAccountsState]: ImportAccountsState[K] extends StateVariable<infer U> ? U : never }
内容的提问来源于stack exchange,提问作者LazioTibijczyk
相关产品推荐
相关产品推荐

