microsoft / microsoft/TypeScript

Ignored check result of typeof a === typeof b

Open
#28,144 2 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.2.0-dev.20181025

Search Terms:

Code

type argType = string | number | boolean;
function sort(a: argType, b: argType): number {
    if (typeof a !== typeof b) {
        return 0;
    }
   // typeof a should be number now
    if (typeof a !== 'number') {
        return 0;
    }
    // typeof b should be number now
    return a - b; // Here TS is not sure that b is number
}

Expected behavior:
We have already checked that typeof a is equal typeof b. So if typeof a is number, than and b is number too.

Actual behavior:
error: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

Playground Link: http://www.typescriptlang.org/play/#src=%0D%0Atype%20argType%20%3D%20string%20%7C%20number%20%7C%20boolean%3B%0D%0Afunction%20sort(a%3A%20argType%2C%20b%3A%20argType)%3A%20number%20%7B%0D%0A%20%20%20%20if%20(typeof%20a%20!%3D%3D%20typeof%20b)%20%7B%0D%0A%20%20%20%20%20%20%20%20return%200%3B%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%20if%20(typeof%20a%20!%3D%3D%20'number')%20%7B%0D%0A%20%20%20%20%20%20%20%20return%200%3B%0D%0A%20%20%20%20%7D%0D%0A%0D%0A%20%20%20%20return%20a%20-%20b%3B%0D%0A%7D

Related Issues:

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the TypeScript code sample and Playground link, then reproduce the reported error using the stated TypeScript 3.2.0-dev.20181025 version or a current build. Investigate control-flow narrowing for typeof a !== typeof b before the arithmetic expression. Done means the example correctly recognizes b as a number without weakening related type checking.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.