Search code examples
javascriptflowtypetypechecking

incompatible type error facebook flow


I have a variable that could be an array of objects, an array of numbers, a nested array of objects or a nested array of numbers. My function deals with each of these cases in turn, but I'm trying to make my code type safe using Facebook flow and I get an incompatible type error.

type Data = number[] | {}[] | Array<{}[]> | Array<number[]>

function parseData(data = Data) {
    ...
}

When I run flow I get

build/js/helpers.js:2
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                 ^^^^^^ number. This type is incompatible with
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                            ^^ object type

build/js/helpers.js:2
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                 ^^^^^^ number. This type is incompatible with
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>

build/js/helpers.js:2
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                 ^^^^^^ number. This type is incompatible with
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                                                       ^^^^^^^^ array type

build/js/helpers.js:2
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                            ^^ object type. This type is incompatible with
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                 ^^^^^^ number

build/js/helpers.js:2
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                                         ^^^^ array type. This type is incompatible with
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                 ^^^^^^ number

build/js/helpers.js:2
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                                                       ^^^^^^^^ array type. This type is incompatible with
  2: type Data = number[] | {}[] | Array<{}[]> | Array<number[]>
                 ^^^^^^ number

I understand that it's saying a variable that is an array of numbers cannot be an array of objects, and neither can be an array of arrays, but I don't know how to type this variable.


Solution

  • You are using the type wrong in your parameters. So this line:

    function parseData(data = Data) {
    

    should be replaced with this line:

    function parseData(data: Data) {
    

    If you use the assignment operator, you basically define a default value for the parameter. So instead of the assignment operator you need to use the colon character to mark the parameter of a specific type.

    At least I get no more errors in the online flow checker here