如何为无关类型声明访问泛型类型?以React.Context<T>为例
能否从无关类型中访问泛型类型参数?
TypeScript本身没有内置方式直接从泛型实例化后的类型中提取原始泛型参数,因为泛型参数在编译后的类型信息中是被封装的,除非目标类型主动暴露了这些参数。
针对React.Context的简洁提取方案
你之前通过propTypes和nominalTypeHack的写法依赖于React内部实现细节,稳定性不足。其实可以利用TypeScript的条件类型推断,直接从React.Context类型中提取泛型参数T:
import { SomeContext } from '@somelib/someContext'; // 定义通用的上下文类型提取工具 type ExtractContextType<C extends React.Context<any>> = C extends React.Context<infer T> ? T : never; // 提取目标上下文的类型 type SomeContextType = ExtractContextType<typeof SomeContext>;
这种写法完全是类型层面的操作,不依赖任何运行时工具,比你之前的实现简洁且可靠。
关于你想要的GenericTypes式写法
TypeScript没有内置的GenericTypes工具来直接获取任意泛型类型的参数列表——不同泛型类型的结构差异极大,无法统一处理。但你可以针对特定泛型类型(比如React.Context、Promise等)编写专用提取工具,例如:
// 提取Promise的泛型参数 type ExtractPromiseType<P extends Promise<any>> = P extends Promise<infer T> ? T : never; // 提取Array的泛型参数 type ExtractArrayType<A extends Array<any>> = A extends Array<infer T> ? T : never;
最稳妥的方案
如果上下文是你自己维护的,显式声明并导出泛型参数类型是最清晰且不易出错的方式:
// 显式声明上下文类型 export type SomeContextType = { username: string; theme: string }; // 创建上下文时复用该类型 export const SomeContext = React.createContext<SomeContextType>({ username: '', theme: 'light' });
后续在需要用到上下文类型的地方,直接导入SomeContextType即可,无需额外提取。
内容的提问来源于stack exchange,提问作者NotX
相关产品推荐
相关产品推荐

