Type narrowing not happening with generics

28 Views Asked by At

Using types to restrict the possible representation of data I have, the values I consider here can be of two kinds: Foo or Bar (aliases of string). As far as I can tell, it means that all values I consider are of kind Foo | Bar.

Now, I want to write a function equal that takes two parameters that must be of the same type. I would like the code to fail to compile if two parameters of different types are given.

I tried to use generics, and type constraints:

type Foo = string;
type Bar = string;
type FooBar = Foo | Bar;

function equal<T extends FooBar>(n1: T, n2: T): boolean {
  return n1 === n2;
}

const n1: Foo = "foo";
const n2: Bar = "bar";

equal(n1, n2);

Sadly, this code compiles... I would like it to fail saying that n1 and n2 should be of the same narrow type. I am suspecting some kind of polymorphism / type widening to be the culprit: it seems that the compiler sees them both of the wide type FooBar.

How can I express that T should be either Foo or Bar, but not FooBar?

0

There are 0 best solutions below