Reputation: 53
I'm wondering if it's possible to create a disjoint union type with a catch all. My idea if that if say the objects 'type' field is a certain value then I know I will have more data available.
I'm thinking it will look something like this:
type MyObject =
| { type: 'extra_details', moreDetails: {here: 'it is'} }
| { type: string }
Thanks!
Upvotes: 0
Views: 156
Reputation: 4310
There is a chapter about Tagged unions in the docs. https://flowtype.org/docs/dynamic-type-tests.html#tagged-unions
But a check like
function foo(x: MyObject) {
if (x.type === 'extra_details') {
// ...extra details code-path
}
}
is not sufficient to prove to flow that in this code-path, x
can only be the extraDetails type. The check satisfies both types of the union. {type: string}
is a more general case of {type: 'extra_details'}
. You can can however check for the existence of the extra fields instead.
if (x.moreDetails) {
}
Upvotes: 1