microsoft / microsoft/TypeScript
Type inference/narrowing lost after assignment
Open
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'.
Related Issues: #18840, #19955, #26673
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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