问题:
假设我有一个来自使用泛型的第三方库的接口
interface SomeInterface<T> {
...
}
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我有一个实现该接口的实例
const someInstance; // type signature: SomeInterface<string>
Run Code Online (Sandbox Code Playgroud)
鉴于此实例,我将如何访问该实例的泛型类型参数 T 的类型(在此示例中,我将如何从中提取string类型someInstance)?我在运行时不需要它,我只需要它,以便我可以定义期望作为函数参数的类型:
function someFunction(someArg: ???) {...}
Run Code Online (Sandbox Code Playgroud)
基本上我希望能够做到这一点,但这是行不通的:
function someFunction(someArg: typeof T in someInstance) {...}
Run Code Online (Sandbox Code Playgroud)
具体用例:
我在这里的具体用例是我正在使用redux-act和redux-sagas包。Redux-act 提供了一个动作创建者工厂,它产生一个类型签名为的动作创建者ActionCreator<P, M>
// someActionCreator has type signature of ActionCreator<string, void>
const someActionCreator = createAction<string, number>(...);
Run Code Online (Sandbox Code Playgroud)
当这个动作创建者被调用通过时someActionCreator(payload: P, metadata: M),它会产生一个Action<P, M>.
// someAction has a type signature of Action<string, number>
const someAction = someActionCreator("foo", 1);
Run Code Online (Sandbox Code Playgroud)
在 redux …