Learning TypeScript 04 — Generics
Mmmm generics, generics are the next level when you’re talking about reusability. They give to us the ability to work with a lot of different types in the same class, but if you want a more academic definition, you will find it here.
Working with functions
Let’s create our first generic 😁
function developing<T>(dev: T): T {...}
A function called developing, that expects a parameter of type Generic and returns a value of the same Generic type.
developing<string>('Maya'); // Ok
developing<number>(11); // Ok
developing<Developer>(new Developer()); // Ok
developing<string>(true'); // Not ok
Wow, amazing, but maybe not so productive, for now.
Working with classes
But you can also use it on classes and interfaces, let’s see a real (and usual) example:
If you want to create a list of elements and you want methods to add or remove elements you can create something similar to this:
class List {
constructor(private items: any[]) {...}
add(item: any): void {...}
remove(i: number): any {...}
count(): number {...}
}let names = new List(['a', 'b']);
let numbers = new List();
numbers.add(2);
numbers.add(8);
numbers.count(); // 2
let devs = new List();
devs.add(new Developer());
And this works but…
let names = new List(['a', 3]);
let numbers = new List();
numbers.add(2);
numbers.add('hehe');
numbers.count(); // 2
let devs = new List();
devs.add(new Developer());
devs.add(4);
Don’t worry, trust the superpowers of generics:
class List<T> {
constructor(private items: T[]) {...}
add(item: T): void {...}
remove(i: number): T {...}
count(): number {...}
}let names = new List<string>(['a', 'b']);
let numbers = new List<number>();
numbers.add(2);
numbers.add(8);
numbers.count(); // 2
let devs = new List<Developer>(); // or new List<IDeveloper>(); 😉
devs.add(new Developer());
Now you cant use data that is not of the type that you have defined when you created the list, is awesome.
If you want, you can start to do things more complex, but only if you want:
class Developer<T, U> {
constructor(private a: T, private b: U) { }
get(): [T, U] {
return [this.a, this.b]
}
}let dev = new Developer<number, string>(10, 'Quique');
And more…
class Developer<T, U, V> {
constructor(private a: T, private b: U, private c: V) { }
get(): [T, U, V] {
return [this.a, this.b, this.c]
}
}let dev = new Developer<number, string, boolean>(10, 'Quique', false);
Yes, they can be as crazy as we want 😵
You can find more info about this article in the official guide.
And info about why I’m doing this articles about TypeScript.
Let’s continue with the next chapter: Decorators.
And remember, feedback is welcome 🤙.