Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 314
Luke101 Avatar asked Aug 27 '16 02:08

Luke101


People also ask

What is F bounded polymorphism?

F-bounded polymorphism (a.k.a self-referential types, recursive type signatures, recursively bounded quantification) is a powerful object-oriented technique that leverages the type system to encode constraints on generics.

What is type T in TypeScript?

This article opts to use the term type variables, coinciding with the official Typescript documentation. T stands for Type, and is commonly used as the first type variable name when defining generics. But in reality T can be replaced with any valid name.

What is as in TypeScript?

The as keyword is a Type Assertion in TypeScript which tells the compiler to consider the object as another type than the type the compiler infers the object to be.


1 Answers

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!*
like image 192
Norguard Avatar answered Sep 28 '22 02:09

Norguard