Simon Long
Simon Long

Reputation: 1450

How do I satisfy an "inexact function" error in Flow?

Ok so I've got a pretty straightforward scenario which works but my issue is keeping flow happy.

const StatusImage: React$Element<*> =
            props.statusImage ? (props.statusImage) : ((): React$Element<*> => <div/>);

I want to display a StatusImage within my React component if the user of the component supplies one through the statusImage prop. Otherwise I just want to leave the space where the icon would be blank.

It works but I get the following flow error which I can't solve. I'm using flow-bin version 0.113.0


Cannot assign props.statusImage ? props.statusImage : (...) => <div /> to StatusImage because inexact function [1] is
incompatible with exact React.Element [2].

 [2] 121|         const StatusImage: React$Element<*> =
 [1] 122|             props.statusImage ? (props.statusImage) : ((): React$Element<*> => <div/>);

I've google the inexact function flow error but can't find anything anywhere that solves my issue. This appears to be quite a new error which has only started to be checked for recently in flow.

Upvotes: 0

Views: 1095

Answers (2)

user11307804
user11307804

Reputation: 828

I would recommend using the React.ComponentType<Props> type if props.statusImage can contain a stateless functional component or a class component. If props.statusImage can only be a stateless functional component then you could use React.StatelessFunctionalComponent<Props>.

import * as React from "react";

type StatusImageComponent = React.ComponentType<{}>;

type Props = { statusImage?: StatusImageComponent };

function Foo(props: Props) {
  const StatusImage =
    props.statusImage === undefined ? () => <div /> : props.statusImage;
  return (
    <div>
      <StatusImage />
    </div>
  );
}

Try Flow

Upvotes: 1

Simon Long
Simon Long

Reputation: 1450

With some further trial and error this seems to work....

 const StatusImage: React$Element<*> | () => React$Element<*> =
            props.statusImage ? (props.statusImage) : ((): React$Element<*> => <div/>);

Upvotes: 0

Related Questions