Skip to content

Improve type narrowing when working with genericsΒ #55060

Closed
@iscekic

Description

@iscekic

Bug Report

πŸ”Ž Search Terms

type narrowing, generics

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing

⏯ Playground Link

https://www.typescriptlang.org/play?#code/KYOwrgtgBAou0G8BQUoEEoF4oEYA0KUAQllAExIC+SSALgJ4AOws8ACgIYCWATqcqgDacSADo0AXQBcUAaigAPGfABGwHgG5ClLYWHxRRabMKp6yyGs3at1JAGMA9iADOtKBA4BrYJ16kAHgAVKGAFWlAAExdWSAA+AAoAM143GSC8KBdgJxBImREIPx5BIIkASiw4k1QuJKhk1PdMFtiIcUq5VFyXRwAbYFE+xwBzBOzcyNEFcu0qJCA

πŸ’» Code

enum Enum {
  A = 1,
  B = 2
}

type EnumPair = {
  [Enum.A]: {
    x: number;
  };

  [Enum.B]: {
    y: number;
  };
}

const makePair = <T extends Enum>(first: T, second: EnumPair[T]) => {
  if (first === Enum.A) {
    console.log(second.x)
  }
}

πŸ™ Actual behavior

Property 'x' does not exist on type '{ x: number; } | { y: number; }'.
  Property 'x' does not exist on type '{ y: number; }'.(2339)

πŸ™‚ Expected behavior

I expected typescript to narrow the type of T to the specific enum being used (due to the equality operator), and therefore the enum pair too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions