Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify one of two props required in Flowjs?

Tags:

flowtype

I have various React components that can have different functionality when different props are passed in. Often I come across some branching logic where if prop1 is present, do one thing, but if prop2 is present do something else.

One example could be two change handlers for an element with an input that take different arguments.

Is there a way to specify in Flowjs that one of the two handlers are required?

like image 410
jmancherje Avatar asked Sep 19 '16 20:09

jmancherje


1 Answers

Fortunately, the Flow type annotation that you want can be applied in contexts beyond React. Generally, if you want an exclusive-or type check you can do this:

type Something = {
    prop1: number,
    prop2?: null
}

type Another = {
    prop1?: null,
    prop2: number
}

function foo(parameter: Something | Another) {

}

foo({ prop1: 10 }); // Good
foo({ prop2: 10 }); // Good
foo({ prop1: 10, prop2: 10 }); // Bad

If you want an inclusive-or type check, you can do this:

type Something = {
    prop1: number,
    prop2?: null
}

type Another = {
    prop1?: null,
    prop2: number
}

type SomethingAndAnother = {
    prop1: number,
    prop2: number
}

function foo(parameter: Something | Another | SomethingAndAnother) {

}

foo({ something: 10, prop1: 10 }); // Good
foo({ something: 10 }); // Bad
foo({ prop1: 10 }); // Good
foo({ prop2: 10 }); // Good
foo({ prop1: 10, prop2: 10 }); // Good

In React, you define the type on the props property, like so:

class TodoList extends React.Component {
  props: Something | Another;

  render(): React.Element {
    return (
      // ....
    )
  }
}
like image 177
Sal Rahman Avatar answered Oct 22 '22 05:10

Sal Rahman