[Typescript + React] Tips: Write your own 'PropsFrom' helper to extract props from any React component

Type helpers change the game when it comes to types in your codebase. They help TypeScript infer more from your code - and make your types a lot more readable.

import React from "react";

const MyFCComponent = (props: { enabled: boolean }) => {
  return null;
};

class MyClassComponent extends React.Component<{
  enabled: boolean;
}> {}

type PropsFrom<TComp> = TComp extends React.FC<infer Props> 
  ? Props 
  : TComp extends React.Component<infer Props>
    ? Props
    : never;

const props: PropsFrom<typeof MyFCComponent> = {
  enabled: true
};

const props2: PropsFrom<MyClassComponent> = {
  enabled: true
};

 

posted @ 2022-10-04 14:06  Zhentiw  阅读(5)  评论(0编辑  收藏  举报