Eslint-plugin-react: [react/prop-types] Doesn't detect TypeScript types for destructured default prop values

Created on 21 Aug 2020  路  3Comments  路  Source: yannickcr/eslint-plugin-react

The bug

TypeScript infers the type of a destructured property when given a default value, for example bar is of type string:

function Foo({ bar = "" }): JSX.Element {
  return <div>{bar}</div>;
}

This same syntax can also be used while explicitly defining the type:

function Foo({ bar = "" as string }): JSX.Element {
  return <div>{bar}</div>;
}

Here's the issue: Despite types being defined, both of the above examples result in the error react/prop-types: 'bar' is missing in props validation.

Current working version

I'm aware that defining the type for the entire object does work, but it's also redundant and doesn't result in any types being different:

function Foo({ bar = ""}: { bar: string }): JSX.Element {
  return <div>{bar}</div>;
}

Notes

All three versions are interpreted by TypeScript as having the exact same type (verified using my editor's tsserver plugin):

function Foo({ bar }: {
    bar: string;
}): JSX.Element

Desired behavior

The first two examples listed above should also pass the prop-types lint check.

enhancement help wanted typescript

Most helpful comment

I'll try for the first contribution 馃槂

All 3 comments

I'll try for the first contribution 馃槂

Not sure if this is related or should be a separate issue.

The below checks fine in version 7.20.5 and throws these errors in 7.20.6.

error propType "width" is not required, but has no corresponding defaultProps declaration react/require-default-props
error propType "height" is not required, but has no corresponding defaultProps declaration react/require-default-props

export type Item = {
  name: string;
  label: string;
};

type Props = Item & {
  width?: 'regular' | 'large';
  height?: number;
};

const MyComponent = ({
  name,
  label,
  height = 8,
  width = 'regular',
}: Props) => {
  return ...
}

Hi, @blumendorf .
Because 7.20.5 is not support typescript TSTypeAliasDeclaration and TSIntersectionType, eslint will ignore the propType check.
After upgrade to 7.20.6, this feature is supported, so it will do the propType check.
Related rule: require-default-props
And your situation should not be related to this issue, seems eslint do not consider your height and width default value as a defaultProps. So this is an issue about the defaultProps detection.
If you don鈥檛 mind, could you create another issue so we can get into it, thanks!

Was this page helpful?
0 / 5 - 0 ratings