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.
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.
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.
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.
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!*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With