How to define defaultProps for a stateless react component in typescript?

前端 未结 2 768
小蘑菇
小蘑菇 2020-12-19 07:05

I want to define defaultprops for my pure functional component but I get a type error:

export interface PageProps extends React.HTMLProps

        
相关标签:
2条回答
  • 2020-12-19 07:51

    This is fairly straightforward by using Javascript's own default function parameters, and with Typescript generics you will get strong correct type information both inside the component and in the outside world of component consumers.

    import React, { FC } from "react";
    
    interface MyComponentProps {
      name?: string;
    }
    
    const MyComponent: FC<MyComponentProps> = ({ name = "Someone" }) => {
      // note that Typescript knows that the property will never
      // be `undefined` inside this function
      return <div>Hello {name}</div>;
    }
    
    export default MyComponent;
    

    And you can consume the component like so:

    import React, { FC } from "react":
    import MyComponent from "./MyComponent";
    
    const ParentComponent: FC = () => {
      // Typescript knows that you name is optional
      // and will not complain if you don't provide it
      return (
        <div>
          <MyComponent />
          <MyComponent name="Jane" />
        </div>
      );
    }
    
    export default ParentComponent;
    
    0 讨论(0)
  • 2020-12-19 08:05

    You can type Page like this:

    const Page: StatelessComponent<PageProps> = (props) => (
        // ...
    );
    

    Then you can write Page.defaultProps without needing to cast to any (the type of defaultProps will be PageProps).

    0 讨论(0)
提交回复
热议问题