Skip to content

Type narrowing is not propagated to a nested discriminated unionΒ #57218

Closed as not planned
@undsoft

Description

@undsoft

πŸ”Ž Search Terms

type narrowing, discriminated union, type narrowing propagation, nested type narrowing

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ.

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.3.3&ssl=36&ssc=2&pln=27&pc=14#code/KYOwrgtgBAygDsAxgS2AZygbwFBSgEQHsBzAGlygGEBDAF2wF9ttkRbgAnAM2sWAJJYKaBCnQAuWKNRoAdEWIBuCgCNCHANaSAFAEooAXgB8UAG6FkAE2VMWbTjz5U6QvCKQzJ8D+lk1aNsy0AJ4IUACCIMgQ1AA2hs60UAA+AkpBofyR0XEA8lwAKpkAPDBQwAAe7CCWGN5iaCYGUACiVRy8tMXZMbGkWFDuDV5QDEbK2CFhPXEA6si0ABb5XCIcrMSl5VWgtVI+jQkzsflFCKUmAGQDhFyrcOsgxJLHpyUwJgwTscBJaIQQYDHBKYBhQagYY7zJYrNYbUrSdDjFhcKDaf6A46yIYyQwGZr1GTyEj6HBuAFAqK9WRqTR6RRQAD0jKguQA0sIKVjbvdHsQaeoNPSmSyAAocQgIDghKAAclpGllUEshHQUBAhCSlWQaCShBAUCm-Flr0K70RjVljGYzKgs0F1AlYBq2EqcHUSSNUAAYsgKsBLFCFss7nCniCKABtMqsfYNAC6Lypc2DsIe8I+jGjFvj31+4I1S04wOaoPBGF9-sDydi0JDvI2ymQqO01ELi2LNexFrxBItxOIpIobc1HY4WIVwtt7OH7c7OVish5Yf5k90DOnHIYQA

πŸ’» Code

enum Species {
  Dog,
  Cat
}

interface Dog {
  species: Species.Dog;
  bork: () => void;
}

interface Cat {
  species: Species.Cat;
}

type Animal = Cat | Dog;

type AnimalOfType<S extends Species> = Extract<Animal, { species: S }>;

type AnimalWithOffspring<S extends Species> = AnimalOfType<S> & { offspring: AnimalOfType<S> };

let someAnimal = {} as AnimalWithOffspring<Species>;
if (someAnimal.species === Species.Dog) {
  someAnimal.bork(); // OK
  someAnimal.offspring.bork(); // Property 'bork' does not exist on type 'AnimalOfType<Species>'
}

πŸ™ Actual behavior

I get an error of Property 'bork' does not exist on type 'AnimalOfType<Species>' because type narrowing did not propagate to offspring.

πŸ™‚ Expected behavior

Offspring type is narrowed to the same animal as parent.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions