How to define defaultProps for a stateless component in typescript?

I want to define defaultpropsfor my pure functional component, but I get an error like:

export interface PageProps extends React.HTMLProps<HTMLDivElement> {
    toolbarItem?: JSX.Element;
    title?: string;
}

const Page = (props: PageProps) => (
    <div className="row">
        <Paper className="col-xs-12 col-sm-offset-1 col-sm-10" zDepth={1}>
            <AppBar
                title={props.title}
                zDepth={0}
                style={{ backgroundColor: "white" }}
                showMenuIconButton={false}
                iconElementRight={props.toolbarItem}
            />
            {props.children}
        </Paper>
    </div>
);

Page.defaultProps = {
    toolbarItem: null,
};

I know I can write this:

(Page as any).defaultProps = {
    toolbarItem: null,
};

Is there a better way to add defaultprops?

+5
source share
2 answers

You can enter Pageas follows:

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

Then you can write Page.defaultPropswithout the need to cast to any(the type defaultPropswill be PageProps).

+8
source

, Javascript , Typescript , .

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;

:

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

Source: https://habr.com/ru/post/1654464/


All Articles