facebook / facebook/flow

Flow does not accept intersection function types even with disjoint unions

Open
#3,021 12 comments 3 reactions 0 assignees View on GitHub
feature request Typing: unions/intersections
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

Hi!

I have the following code ([try link](https://flowtype.org/try/#0C4TwDgpgBAglC8UDeAoKVSQFxQOQENcAaNKfHAZ2ACcBLAOwHMSBfAbhRU2gCEFlS3HLgBGxUiJz0ArgFsREaqw5dw0AGL8AFFvKwAlAgB8UKnSaGAZFB2SoPQ-BMz5i-RwDGAe3pUoAMy8vHE1EXTs4AB97RxNUdFp-G3wRADpuBHhEAlxDePQoaghgaWp6MjT8DnQWKAgAGwpofPQikrKK1JFqqBYUFiA))

```jsx
type A = {
type: 'a',
a: string,
};

type B = {
type: 'b',
b: number,
};

type F = ((a: A) => string) & ((b: B) => number);
const foo: F = (ab: A | B) => {
if (ab.type === 'a') {
return ab.a;
} else {
return ab.b;
}
}
```

I wish to make a function `foo` accepting a disjoint union but which returns different types for each member.

This fails with the following error:
```
14: return ab.a;
^ string. This type is incompatible with
11: type F = ((a: A) => string) & ((b: B) => number);
^ number
16: return ab.b;
^ number. This type is incompatible with
11: type F = ((a: A) => string) & ((b: B) => number);
^ string
```

What's the best way to express this type of function (disjoint types input, but different output type for each one)? I would like to not have to declare it as `(ab: A|B) => string|number` because that loses some information.

Sincerely,
Dan

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.