React with TypeScript - define defaultProps in stateless function

前端 未结 7 1564
梦如初夏
梦如初夏 2021-02-01 04:56

I\'m using React with TypeScript and I\'ve created stateless function. I\'ve removed useless code from the example for readability.

interface CenterBoxProps exte         


        
7条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 05:12

    Typing default props in function component with React.FC can result in false type error:

       type Props = {
         required: string,
       } & typeof defaultProps;
    
       const defaultProps = {
         optDefault: 'optDefault'
       };
    
       const MyComponent: React.FC = (props: Props) => (
         
    • required: {props.required}
    • optDefault: {props.optDefault}
    ) MyComponent.defaultProps = defaultProps; ReactDOM.render(
    , document.getElementById('app') );

    error:

    [tsserver 2741] Property 'optDefault' is missing in type '{ required: string; }' but required in type '{ optDefault: string; }'. [E]
    

    Another solution proposed is to use Javascript's own default function parameters:

    type Props = {
      required: string,
      optDefault?: string
    }
    
    const MyComponent:  React.FC = ({
      required,
      optDefault='default'
    }: Props) => (
      
    • required: {required}
    • optDefault: {optDefault}
    ) ReactDOM.render(
    , document.getElementById('app') );

    But the problem with this solution is that if you forgot to provide default, a run time bug will result:

    const MyComponent: React.FC = ({
      required,
      optDefault //='optDefault' //<--- if you forgot to provide default
    }: Props) => (
      
    • required: {required}
    • optDefault: {optDefault}
    • {/* <-- result in bug */}
    )

    A better solution is not using React.FC at all, simply rely on Typescript type inference:

    type Props = {
      required: string,
    } & typeof defaultProps;
    
    const defaultProps = {
      optDefault: 'optDefault'
    };
    
    const MyComponent = (props: Props) => (
      
    • required: {props.required}
    • optDefault: {props.optDefault}
    ) MyComponent.defaultProps = defaultProps ReactDOM.render(
    , document.getElementById('app') );

提交回复
热议问题