facebook / facebook/flow

type refinement with typeof not working

Open
#7,252 2 comments 4 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

[try flow](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagIKgLygDeAPoqKAIYBcoAzsgE4CWAdgOYA05oAxrawCuAWwBGmRohIBfANyIUGbACECxMhVG0GLDtwoATASPGSZ8xVlyrCeEqGUXMAD3SxGyPrFYNQ7TMgAciYSagAUlFrWAJTGYqH4AHw8aFiwkFSiAHSUBPiEAOQ6bOwFoAD8mVm8oLSRWQayQA)

same example with same key but different type:
[try flow](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagIKgLygDeAPoqKAIYBcoAzsgE4CWAdgOYA05oAxrawCuAWwBGmRohIBfANyIUGbACECxMhRqghYidwoATASPGSZ8xVlyrCeEqGUXMAD3SxGyPrFYNQ7TMgAciYSagAUlKK0OMoAlMa6jAQAfDxoWLCQVKIAdJQE+IQA5AwsHEWgAPzZObygtJE5BrJAA)

following code:

```
// @flow
type A = {|
a: string,
c: number
|};

type B = {|
b: string,
d: number
|};

type AB = A | B;

export const getNumber = (ab: AB): number =>
typeof ab.a === 'string' ? ab.c : ab.d;
```

gives following error:

```
15: typeof ab.a === 'string' ? ab.c : ab.d;
^ Cannot get `ab.c` because property `c` is missing in `B` [1].
References:
14: export const getNumber = (ab: AB): number =>
^ [1]
15: typeof ab.a === 'string' ? ab.c : ab.d;
^ Cannot get `ab.d` because property `d` is missing in `A` [1].
References:
14: export const getNumber = (ab: AB): number =>
^ [1]
```

It's clear that when `ab.a` is a string, it should have property `c`, and otherwise it should have property `d`.

Anyhow, with string literals the refinement is working: [try flow](https://flow.org/try/#0PTAEAEDMBsHsHcBQAXAngBwKagIKgLygDeAPoqKGlgFygDkAhnQDTmgO0DOyATgJYA7AOasKAY1oCArgFsARph6ISAXwDciFBmwAhAsTIUqmWnTks2HUNPmLRoACaTZCpao1asuPYTwlQOh6YAB7osDzIoGKwAtygQpjIAHIuivoAFAxytDg6AJTOtjwEAHyWcgB0xgT4hIx0oAD87JVioLRZFQ5qQA)

This is something that people expects flow to shine, but when it's not working it causes easily great frustration.

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.