microsoft / microsoft/TypeScript

Type inference/narrowing lost after assignment

Open
#27,706 16 comments 31 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.1

Search Terms: type inference, type guard, narrowing, lost, assignment

Code

let a: unknown = 'x';

if (typeof a === 'string') {
  // a inferred as `string`
  a = a.substr(0, 5);  // (method) String.substr(from: number, length?: number): string
  // a inferred as `unknown`
  a.length;            // Failure: Object is of type 'unknown'.
}

Expected behavior: This should compile without an error.

Actual behavior: Line 7 fails with: Object is of type 'unknown'.

Playground Link: https://www.typescriptlang.org/play/index.html#src=let%20a%3A%20unknown%20%3D%20'x'%3B%0D%0A%0D%0Aif%20(typeof%20a%20%3D%3D%3D%20'string')%20%7B%0D%0A%20%20%2F%2F%20a%20inferred%20as%20%60string%60%0D%0A%20%20a%20%3D%20a.substr(0%2C%205)%3B%0D%0A%20%20%2F%2F%20a%20inferred%20as%20%60unknown%60%0D%0A%20%20a.length%3B%0D%0A%7D%0D%0A

Related Issues: #18840, #19955, #26673

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

Reproduce the minimal example in the TypeScript Playground and compare its behavior with related issues #18840, #19955, and #26673. The work is complete when the assignment inside the typeof guard preserves the string narrowing so the final a.length expression compiles without an error.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.