November 2019
Beginner
804 pages
20h 1m
English
Let's go through one more example to show how we can link the input and output types of a function thanks to generics.
Suppose that we want to write a function that accepts different types as input and returns the same types as output. Without generics, we would need to rely on any, which would mean losing valuable type information. With generics, we can define the function as follows:
function log<T>(arg: T): T {
console.log("Log entry: ", arg);
return arg;
}
class Person {
constructor(private name: string){}
}
const person: Person = log(new Person("foo"));
In this case, the log function's return type will always match the argument type.
Read now
Unlock full access