Skip to content

Union types in generics do not correctly check types.Β #46552

Closed

Description

Bug Report

πŸ”Ž Search Terms

union generic implicit

πŸ•— Version & Regression Information

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

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface TwoSameTypes<T> {
  a: T;
  b: T;
}

// @ts-expect-error
const x : TwoSameTypes<Number | String> = {
  a: 1,
  b: "string", // <-- This does not give an error, because `b` has the type `String | Number`
}

πŸ™ Actual behavior

No error happens

πŸ™‚ Expected behavior

I would expect an error for the value of x because both a and b are expected to have the same type, but they don't in this case.

For the record, and as can be seen from the playground link, when doing TwoSameTypes<Number> | TwoSameTypes<String> instead of TwoSameTypes<Number | String> we do end up with the desired behaviour. But I think these two different ways of defining are equivalent? So it seems like the latter way of doing it should work as well.

Furthermore, here's demo of a use case for this behaviour. I would like to use keyof ValueMap as the generic type, so I don't have to type every possible enum twice.

Apologies in advance if this is a duplicate, I wasn't able to find the right keywords to describe this behaviour.

Activity

  1. jespertheend commented on Oct 27, 2021

    @jespertheend
    ContributorAuthor

    Ah sorry, I wasn't aware this was intentional. Thanks for example!

  2. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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