facebook / facebook/flow

Assert non primitive types in comparison expression

Open
#6,307 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

Using `==` for comparing primitive values, Flow [warns](https://flow.org/try/#0DYUwLgBAhhC8ECIDOYBOBLAdgcwQbgChRIAjOCAZgDoBGAFkOIgGNyZZ4TCg) about type difference.

In:

```
let a = "string";
let b = 3.14;
let c = a == b;
```

Out:

```
3: let c = a == b;
^ Cannot compare string [1] to number [2].
References:
1: let a = "string";
^ [1]
2: let b = 3.14;
^ [2]
```

Though, [it doesn't happen](https://flow.org/try/#0C4TwDgpgBAqgzhATlAvFA3lAdgQwLYQBcUcwiAllgOZQC+A3AFCiRQAKOIANgPY4AmqDFHL9ipCtTpNGXCMChjYCZGky4CxAOQAZcgC8cW6bPlQi7TrwFDMo7TgBGAY2MNTCgGZDBKNBCYgA) when objects are compared, especially when types are defined, not inferred.

In:

```
type User = { name: string };
type Payload = { id: string };

let d: User = { name: 'Liza' };
let e: Payload = { id: 'abc' };
let f = d == e;
```

Out: no errors.

Is it expected behavior? TypeScript [handles both cases](https://www.typescriptlang.org/play/index.html#src=let%20a%20%3D%20%22string%22%3B%0D%0Alet%20b%20%3D%203.14%3B%0D%0Alet%20c%20%3D%20a%20%3D%3D%20b%3B%0D%0A%0D%0Alet%20d%20%3D%20%7B%20name%3A%20'Liza'%20%7D%3B%0D%0Alet%20e%20%3D%20%7B%20id%3A%20'abc'%20%7D%3B%0D%0Alet%20f%20%3D%20d%20%3D%3D%20e%3B%0D%0A), even when object types are inferred.

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.