如何从泛型中提取类型?

时间:2021-07-21 06:56:01

标签: reactjs typescript

如何从泛型中提取第一种类型?

const App: FC<number> = () => { }

type FirstTypeFromApp = App[GET_FIRST_GENERIC] ??? // number

如何从number中提取泛型类型App,怎么做?

1 个答案:

答案 0 :(得分:2)

你可以使用 Infer 来做到这一点。

type FC<T> = () => any;
const App: FC<number> = () => { };

type extractGeneric<Type> = Type extends FC<infer X> ? X : never;

type FirstTypeFromApp = extractGeneric<typeof App>;


const x: FirstTypeFromApp = 13221; //String will throw error

这里是游乐场:playgoround