typescript :获取实例的通用类型

标签 typescript generics

问题:

假设我有一个来自使用泛型的第三方库的接口(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-actredux-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 ),其中 PM已定义类型,但我无权访问操作本身。但是,处理函数期望将操作作为参数,例如

function* someEffectHandler(action: Action<string, void>) {...}

因为 Typescript 知道 P 的类型和 MsomeActionCreator ,我希望能够在 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/

相关文章:

generics - 如何处理从 Java 迁移到 Kotlin 的通用边界?

reactjs - 如何在 typescript 中设置初始 React 状态?

javascript - 从 Angular 字符串中删除特殊字符

golang protobuf 无法在泛型类型中解码

java - 有没有办法在类类型的定义中重用通用通配符?

c# - 将 Expression<T, string>> 转换为 Expression<T, bool>>

java - 为什么这种通用分配是非法的?

javascript - Angular 2 "this"无法访问嵌套函数中的全局变量

typescript - 将原始对象转换为类?

reactjs - TypeScript React 中可重用的布局组件 : Property 'path' does not exist on type 'IntrinsicAttributes & IProps'