Skip to content

[react]: defaultProps doesn't work with function component - LibraryManagedAttributes #29816

@Hotell

Description

@Hotell

If you know how to fix the issue, make a pull request instead.

Dependencies:

"typescript": "3.1.3"
"@types/react": "16.4.18",
"@types/react-dom": "16.0.9",

Code Sample:

type Props = {
  onClick: (ev: import('react').MouseEvent<HTMLElement>) => void
  children: import('react').ReactChild
} & typeof defaultProps

const defaultProps = { color: 'red' }

const Button = ({ onClick: handleClick, color, children }: Props) => (
  <button style={{ color }} onClick={handleClick}>
    {children}
  </button>
)
Button.defaultProps = defaultProps

const handleClick = () => console.log('clicked')
const color = 'red'

export const Example = () => (
  <>
    <Button onClick={handleClick}>Click me</Button>
  </>
)

Current Behaviour:

<Button onClick={handleClick}>Click me</Button> will get compile error

 Property 'color' is missing in type '{ children: string; onClick: () => void; }'.

Following code works with class component as expected:

class Button extends Component<Props> {
  static readonly defaultProps = defaultProps
  render() {
    const { onClick: handleClick, color, children } = this.props

    return (
      <button style={{ color }} onClick={handleClick}>
        {children}
      </button>
    )
  }
}

image

Expected Behaviour:

Make default props work for both class and function components

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions