Luke101 Luke101 - 3 months ago 22
TypeScript Question

What is F-Bounded Polymorphism in TypeScript

I notice version 1.8 of TypeScript supports F-Bounded Polymorphism. In layman's terms, what is it and how is this helpful? I am assuming since this feature was included early it must be pretty important.

Answer

It basically means that you have your list of generics that the function references, and within that list of generics, one type can reference another type, to define a relationship between the two generic types.

function someFunction <T, U> (t: T, u: U): T {
  return t;
}

const dog = someFunction(new Dog(), new Cat());

Hooray!

Now, with bounded generics, they can reference one another to define the bounds of the relationship they have with each other:

function someFunction <T extends U, U> (t: T, u: U): T {
  return t;
}

const dog = someFunction(new Dog(), new Pet());
const cow = someFunction(new Cow(), new Animal());
const BOOM = someFunction(new Cat(), new Dog()); // *BEWM!*