Skip to content

Type inference/narrowing lost after assignment #27706

Open
@sgoll

Description

@sgoll

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions