facebook / facebook/flow

Allow refinement of exact object union types with typeof

Open
#4,639 6 comments 15 reactions 0 assignees View on GitHub
Typing: refinements Typing: unions/intersections
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

Refining exact object union types by shape is currently VERY limited. We should be able to refine such types by their shape using `typeof` at the very least, and ideally any other common refinement techniques (`Array.isArray`, etc).

From my perspective [this should work](https://flow.org/try/#0PTAEAEDMBsHsHcBQiAuBPADgU1AMVrKALygDeAPpAQFygDOKATgJYB2A5uQL4DcqmOAEIBDRsTLkARqNoMWHbn3TZQAZVgBbLAFVWzWK3H5C5UCMZ9EkAK6sAxin2H2WFMYDyjAHLXo0UAAU1rTqWrpOAJS0APzGZIgAkIyu1oyGyliwkKDWAHRUhERFoADktgAmWJBsWOUloNGgrL7+tNZ8XIhAA):

```ts
// @flow

type Foo = {|foo: string|};
type Bar = {|bar: string|};
type SomeUnion = Foo | Bar;

function getFooOrNull (u: SomeUnion): ?Foo {
return typeof u.foo === 'undefined' ? null : u;
}
```

but fails with:

```
4: type Bar = {|bar: string|};
^ property `bar`. Property not found in
7: function getFooOrNull (u: SomeUnion): ?Foo {
^ object type
7: function getFooOrNull (u: SomeUnion): ?Foo {
^ property `foo`. Property not found in
4: type Bar = {|bar: string|};
^ object type
```

---

This limitation is also described in [this comment](https://github.com/facebook/flow/issues/3614#issuecomment-290622704), and is related to #4328.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.