问题:
假设我有一个来自使用泛型的第三方库的接口(interface)
interface SomeInterface<T> {
...
}
在我的代码中,我有一个实现该接口(interface)的实例
const someInstance; // type signature: SomeInterface<string>
鉴于此实例,我将如何访问该实例的泛型类型参数 T 的类型(在此示例中,我将如何从 string
中提取 someInstance
类型)?我在运行时不需要它,我只需要它以便我可以定义期望的类型作为函数中的参数:
function someFunction(someArg: ???) {...}
基本上我希望能够做到这一点,但这是行不通的:
function someFunction(someArg: typeof T in someInstance) {...}
具体用例:
我在这里的具体用例是我正在使用 redux-act
和 redux-sagas
包。 Redux-act 提供了一个 action creator 工厂,它生成一个类型签名为 ActionCreator<P, M>
的 action creator。
// someActionCreator has type signature of ActionCreator<string, void>
const someActionCreator = createAction<string, number>(...);
当通过 someActionCreator(payload: P, metadata: M)
调用此 Action 创建器时, 它产生一个 Action<P, M>
.
// someAction has a type signature of Action<string, number>
const someAction = someActionCreator("foo", 1);
在 redux sagas 中,我可以访问 action creator 实例(即 someActionCreator
),其中 P
和 M
已定义类型,但我无权访问操作本身。但是,处理函数期望将操作作为参数,例如
function* someEffectHandler(action: Action<string, void>) {...}
因为 Typescript 知道 P
的类型和 M
在someActionCreator
,我希望能够在 someEffectHandler
的类型声明中访问它们.
我试图避免的是,当 Action 创建者应该能够给我类型化参数时,必须为每个 Action 编写大量样板。
//Trying to avoid this
type SomeActionPayload = string;
type SomeActionMetadata = number;
export type SomeAction = Action<SomeActionPayload, SomeActionMetadata>;
export const someActionCreator = createAction<SomeActionPayload, SomeActionMetadata>(...);
最佳答案
type GetInnerType<S> = S extends SomeInterface<infer T> ? T : never
用法:
type InnerType = GetInnerType<typeof someInstance>
关于 typescript :获取实例的通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48180905/