How to specify (optional) default props with TypeScript for stateless, functional React components?

后端 未结 4 835
清歌不尽
清歌不尽 2021-01-31 07:42

I\'m trying to create a stateless React component with optional props and defaultProps in Typescript (for a React Native project). This is trivial with vanilla JS, but I\'m stum

4条回答
  •  不知归路
    2021-01-31 08:30

    To me, this doesn't look like a typescript issue.

    DISCLAIMER: I have only tried this with typescript.

    However, the problem is that props always exists (even as an empty object when nothing is passed in). There are 2 workaround for this, though.

    The first, unfortunately, kills the super clean curly-brace-less syntax you have, but let's you keep defaultProps around.

    interface TestProps {
        title?: string;
        name?: string;
    }
    
    const defaultProps: TestProps = {
        title: 'Mr',
        name: 'McGee'
    }
    
    const Test = (passedIn: TestProps) => {
        const props = Object.assign({}, defaultProps, passedIn);
        return (
            

    {props.title} {props.name}

    ); }

    another alternative that might get a little hairy if you have a TON of props, but that lets you keep your original syntax is something like this:

    const Test = (props: TestProps) => (
        
            {props.title || 'Mr'} {props.name || 'McGee'}
        
    );
    

    Hope this helps!

提交回复
热议问题