react-docgen icon indicating copy to clipboard operation
react-docgen copied to clipboard

[Typescript] Default props from defaults when destructuring

Open HHogg opened this issue 5 years ago • 4 comments

The defaults work fine from the static .defaultProps property like ...

interface Props {
  foo?: string;
}

const Test: React.SFC<Props> = (props: Props) => {
  const { foo, ...rest } = props;

  return (
    <div { ...rest } />
  );
}

Test.defaultProps = {
  foo: 'bar',
};

export default Test;

I'm wondering if you think it would be possible to get default prop values from the defaults when destructuring during the render? like ...

interface Props {
  foo?: string;
}

const Test: React.SFC<Props> = (props: Props) => {
  const { foo = 'bar', ...rest } = props;

   return (
    <div { ...rest } />
  );
};

export default Test;

HHogg avatar May 08 '19 15:05 HHogg

I guess this could work, also this is not dependent on typescript, this could even be useful with PropTypes.

danez avatar May 22 '19 09:05 danez

I agree, I also see a lot of code where folks destructure the props right in the component function args. In fact, anecdotally, I don't really see defaultProps being used anywhere near as often as setting while destructuring as in the example below. Just want to put my vote in for this.

interface Props {
  foo?: string;
}

const Test: React.SFC<Props> = ({ foo = 'bar', ...rest }: Props) => {

   return (
    <div { ...rest } />
  );
};

export default Test;

warmbowski avatar Mar 30 '20 16:03 warmbowski

An alternative way to allow this, but still get default values out would be to take the jsDoc annotation of a prop and parse out the @defalut as in the example below. Is this an easier way to avoid having to set defalutProps?

interface Props {
  /**
   * value for doing foo
   * @default 'bar'
   */
  foo?: string;
}

const Test: React.SFC<Props> = ({ foo = 'bar', ...rest }: Props) => {

   return (
    <div { ...rest } />
  );
};

export default Test;

warmbowski avatar Mar 30 '20 16:03 warmbowski

Updates on this?

bryanjtc avatar Oct 24 '22 01:10 bryanjtc