A thread complaining about an incompatible type in the default values ​​for objects that destroy

I have this very simple function that I am trying to test with Flow:

// @flow
type Props = {
  width: string | number,
};

function fun({
  width = '30em',
}: Props) {
  return width;
}

The problem is that I get this error:

8:   width = '30em',
     ^ number. This type is incompatible with
8:   width = '30em',
     ^ string
8:   width = '30em',
     ^ string. This type is incompatible with
8:   width = '30em',
     ^ number
8:   width = '30em',
             ^ string. This type is incompatible with
8:   width = '30em',
     ^ number

I wonder what I'm doing wrong ... This method works fine:

// @flow
type Props = {
  width: string | number,
};

function fun(props: Props) {
  const {
    width = '30em',
  } = props;
  return width;
}

And this syntax inside function arguments is supported because:

// @flow
type Props = {
  width: string,
};

function fun({ width = '30em' }: Props) {
  return width;
}

This works great.

Ideas?

+4
source share
2 answers

The default assignment for defragmentation is not supported in the stream.

Instead of assigning default values ​​and destructuring at the same time, you should define the default parameters separately, and then use them as your default values.

For instance:

type Props = {
    width: string | number
}

const defaultProps: Props = {
    width: '30em',
}

function fun ({ width }: Props = defaultProps) {
  return width
}

fun({ width: 30 })   // => 30
fun({ width: '30' }) // => '30'
fun()                // => '30em'

fun({ width: true }) // $ExpectError

.

0

:

const fun: (Props) => string | number = ({
  width = '30em',
}) => {
  return width;
}

, , ​​ . . issue 2198.

0

Source: https://habr.com/ru/post/1680427/


All Articles