TypeScript:如何从类型中提取泛型参数? [英] TypeScript: how to extract the generic parameter from a type?

查看:63
本文介绍了TypeScript:如何从类型中提取泛型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似 React.ComponentClass 的类型,我想引用 Props 部分,但它在我当前的上下文中未命名.

Say I have a type like React.ComponentClass<Props> and I want to reference the Props part but it is unnamed in my current context.

举例说明:

const x = makeComponent(); // typeof x = React.ComponentClass<Something>

在这种情况下,我可以使用 typeof x 但这并没有给我直接访问 Something 类型.

In this situation, I can use typeof x but that doesn't give me direct access to the Something type.

我想要的是这样的:

type GetPropsType<C extends React.ComponentClass<P>> = P

这样我就可以提取 Something 类型为 GetPropsType

So that I can extract Something with the type GetPropsType<typeof x>

任何等效的东西都会很棒.

Anything equivalent would be great.

推荐答案

可以使用 infer:

You can use infer:

type TypeWithGeneric<T> = T[]
type extractGeneric<Type> = Type extends TypeWithGeneric<infer X> ? X : never

type extracted = extractGeneric<TypeWithGeneric<number>>
// extracted === number

游乐场

这篇关于TypeScript:如何从类型中提取泛型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆