microsoft / microsoft/TypeScript

Differing user-defined type guard and 'typeof' type guard behaviour when narrowing 'any'

Open
#6,015 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Effort: Moderate Help Wanted Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

In the below code, using a typeof type guard and an equivalent (I thought) user-defined guard, only one error is produced.

var y: any;

// Built-in type guard
if (typeof y === "string") {
    y.hello = true; // Correct error - 'hello' does not exist on type string
}

// Equivalent user-defined type guard
function f(x: any): x is string {
    return typeof x === "string";
}

if (f(y)) {
    y.hello = true; // No error with user-defined guard
}

Playground demo. Looks like user-defined type guards won't narrow from any, in any circumstances, as far as I can tell.

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 Playground example in the issue and reproduce the differing diagnostics for the built-in and user-defined guards. Trace the compiler's narrowing behavior for an any value and verify that the user-defined guard produces the same error for y.hello as the typeof guard.

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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.