Is there any typescript built-in way to get any component's ( both class or functional) props types? I have been looking for an answer on SO and on the official TypeScript documentation , in vain.
What I ended up doing is the following, which seems to work:
import React from "react";
// My solution
type Props<C> = C extends ComponentType<infer P> ? P : never;
class MyClassComponent extends React.Component<{ classProp1: string, classProp2: number }> { }
const MyFuncComponent: React.FunctionComponent<{ funcProp1: boolean, funcProp2: string }> = () => <></>;
type MyClassProps = Props<typeof MyClassComponent>; // { classProp1: string; classProp2: number; }
type MyFuncProps = Props<typeof MyFuncComponent>; // { funcProp1: boolean; funcProp2: string; }
If there is no built-in way to do so, I will make a suggestion to the Github project. In the mean time, please feel free to improve my way of doing it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.