flow icon indicating copy to clipboard operation
flow copied to clipboard

Issue with propTypes and defaultProps (string vs PropTypes.node)

Open toddw opened this issue 10 years ago • 2 comments

If I have a component with a property with the type PropTypes.node, but I specify a string as the default prop, when I pass a PropTypes.node I get an error saying it should be a string. If I set the default prop to a node and I pass a string, then I get an error saying it should be a React$Element. Is there a work-around for this? It seems reasonable that you should be able to use a string or a node interchangeably.

Example:

import React, { Component, PropTypes } from "react";

export default class MyComponent extends Component {
  static propTypes = {
    name: PropTypes.node
  };

  static defaultProps = {
    child: "…"
  };

  render () {
    return (
      <div>{this.props.name}</div>
    );
  }
}

Then in another file:

import React, { Component } from "react";

export default class Test extends Component {
  render () {
    const name = <span>Name</span>;
    return (
      <div><MyComponent name={name} /></div>
    );
  }
}

You get the error "object type … This type is incompatible … string literal".

If I remove the defaultProps then there is no problem, but I need to be able to specify a fallback.

toddw avatar Apr 26 '16 00:04 toddw

An old thread I know, but would be good to know if there is an issue with what you've implemented or flow? Have encountered the same scenario.

nazimjamil avatar Jul 05 '17 08:07 nazimjamil

There were a number of issues with the intersection of prop and default prop types. They are fixed in Flow v0.53 with changes to the way the Component class is typed.

If I take the example above and just make some minor changes to syntax and renaming, it type-checks just fine.

I believe this issue can be closed. (/cc @calebmer)

asolove avatar Aug 22 '17 01:08 asolove