TypeScript:如何从类型中提取泛型参数?

标签 typescript

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

举例说明:

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

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

我想要的是这样的:

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

这样我就可以提取Something类型为 GetPropsType<typeof x>

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

最佳答案

您可以使用推断:

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

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

Playground

关于TypeScript:如何从类型中提取泛型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44851268/

相关文章:

angular - 显示带有加载和错误情况的数据

javascript - 为什么 Redux.js "Dispatch"TypeScript 接口(interface)有模板参数?

javascript - 当我点击浏览器上的“查看源代码”时,无法查看 Html

arrays - 在 TypeScript 中向类型化数组添加方法

typescript - Webpack 排除规范文件

javascript - 泛型 : Create instance from abstract class

interface - 如何转换为对象可能实现的接口(interface)?

typescript - 声明在编译时有效,但在运行 mocha 测试时无效

具有无限深度的数组的 typescript 类型

typescript - {{myArray}} 数组绑定(bind)未在 View 中更新