首页 > 其他分享 >[Typescript + React] Tips: Write your own 'PropsFrom' helper to extract props from any Rea

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

时间:2022-10-04 14:11:44浏览次数:67  
标签:Write Typescript const React extends props your PropsFrom

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
};

 

标签:Write,Typescript,const,React,extends,props,your,PropsFrom
From: https://www.cnblogs.com/Answer1215/p/16753692.html

相关文章