Skip to content

"in" operator not narrowing the type if used with a const #42639

Description

@kdmadej

Bug Report

🔎 Search Terms

  • narrow in operator
  • in operator
  • narrow operator
  • operator type guard

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about the "in" operator.

Tested on all TS versions available in the playground (at the time of writing: 3.3 - Nightly of 4.2.0)

⏯ Playground Link

Playground link with relevant code

💻 Code

const keywordA = 'a'
const keywordB = 'b'

type A = { [keywordA]: number }
type B = { [keywordB]: string }

declare const c: A | B

if ('a' in c) {
    c // narrowed to `A`
}

if (keywordA in c) {
    c // not narrowed, still `A | B`
}

🙁 Actual behavior

When using a const string as the "prop" argument for the in operator the type of the object is not narrowed.

🙂 Expected behavior

Since I'm using a const, thus dealing with a string literal type (same as when using a literal value as an argument), I'd expect the type to be narrowed inside the if block.

Activity

  1. added
    Experience Enhancement
    Suggestion
    on Feb 4, 2021
  2. RyanCavanaugh commented on Feb 4, 2021

    @RyanCavanaugh
    Member

    I don't see any reason this couldn't be made to work

  3. added
    Fix Available
    on Jul 21, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Experience EnhancementFix AvailableSuggestion

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions