gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:08 25 4
gpt4 key购买 nike

假设我有一个类似 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com