Flow: mixed type in props of React Element. Number is incompatible with string

Created on 11 Aug 2017  路  5Comments  路  Source: facebook/flow

when we set one props to number | string I'm get error.

react element example on try flow

But with one simple function it works correctly.

Maybe I'm doing something wrong?

duplicate unionintersections destructuring

Most helpful comment

Oddly enough this works:

/* @flow */

import React from 'react';

const Square = (props: {
  width?: string | number,
  color?: string,
  className?: string,
  style?: {}
}) => {
  const { width = '10px', color = 'gray', style, className } = props
  return (
    <div
      className={className}
      style={{
        width: width,
        height: width,
        backgroundColor: color,
        ...style,
      }}
    />
  )
}

export default Square;

All 5 comments

Oddly enough this works:

/* @flow */

import React from 'react';

const Square = (props: {
  width?: string | number,
  color?: string,
  className?: string,
  style?: {}
}) => {
  const { width = '10px', color = 'gray', style, className } = props
  return (
    <div
      className={className}
      style={{
        width: width,
        height: width,
        backgroundColor: color,
        ...style,
      }}
    />
  )
}

export default Square;

This should be titled, "Unable to set a subtype default value (function input object destructure)".

Here is a more simple example:

const foo = ({ bar = 'a' }: { bar: number | string }): void => {}
1: const foo = ({ bar = 'a' }: { bar: number | string }): void => {}
                  ^ number. This type is incompatible with
1: const foo = ({ bar = 'a' }: { bar: number | string }): void => {}
                  ^ string
1: const foo = ({ bar = 'a' }: { bar: number | string }): void => {}
                  ^ string. This type is incompatible with
1: const foo = ({ bar = 'a' }: { bar: number | string }): void => {}
                  ^ number
1: const foo = ({ bar = 'a' }: { bar: number | string }): void => {}
                        ^ string. This type is incompatible with
1: const foo = ({ bar = 'a' }: { bar: number | string }): void => {}
                  ^ number

It seems to only be an issue for union subtypes (string <: string | number) & not classes and intersections.

declare var isString: string
const fooUnionExample = ({ bar = isString }: { bar: number | string }): void => {}

declare class Animal {}
declare class Dog extends Animal {}
const fooClassExample = ({ bar = new Dog() }: { bar: Animal }): void => {}

declare var numberAndString: number & string
const fooIntersectionExample = ({ bar = numberAndString }: { bar: number }): void => {}

Duplicate of #2093

Was this page helpful?
0 / 5 - 0 ratings

Related issues

glenjamin picture glenjamin  路  3Comments

jamiebuilds picture jamiebuilds  路  3Comments

funtaps picture funtaps  路  3Comments

cubika picture cubika  路  3Comments

l2silver picture l2silver  路  3Comments