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?
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 (
// ....
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With