Generics
Generic types are like functions for type declarations the let you pass some arguments (other types) later. This is a (part of) simple linked list implementation:
1
type ListNode = {
2
value: any;
3
next: ListNode|null;
4
}
5
6
function add(head: ListNode, value: any): ListNode {
7
const newElement: ListNode = { value, next: null };
8
let current: ListNode = head;
9
10
while (current.next) {
11
current = current.next;
12
}
13
14
current.next = newElement;
15
16
return current;
17
}
Copied!
This code is fine, it works, but gives no type safety:
1
const head: ListNode = {
2
value: 12,
3
next: null
4
}
5
6
add(head, "Hello!")
Copied!
Generics give us a way to specify: this is a LinkedList of numbers. Or strings. Or whatever.

A generic type

This is the same type, but this time written as generic:
1
type ListNode<T> = {
2
value: T;
3
next: ListNode<T>|null;
4
}
Copied!
T is the variable type argument here. When creating the head element we'll specify the type of values in the list:
1
const head: ListNode<number> = {
2
value: 12, next: null
3
}
Copied!
Trying to give different type of value will result in an error:
1
const head: ListNode<number> = {
2
value: "12", next: null
3
}
Copied!

Generic functions

Functions can be generic too! First, let's take a look at a simple example:
1
function makeTuple<T>(a: T, b: T): [T, T] {
2
return [a, b];
3
}
Copied!
Great thing about generic functions is that TypeScript is actually quite smart about them. This obviously works as expected:
1
makeTuple<number>(1, 20);
Copied!
But TypeScript is also to guess the type T based on the first argument it gets.
1
makeTuple("Hello", "Devmeetings")
2
makeTyple("Hello", 13) // error
Copied!
Let's rewrite the add function from previous example:
1
function add<T>(head: ListNode<T>, value: T): ListNode<T> {
2
const newElement: ListNode<T> = { value, next: null };
3
let current: ListNode<T> = head;
4
5
while (current.next) {
6
current = current.next;
7
}
8
9
current.next = newElement;
10
11
return current;
12
}
13
14
15
add(head, 12);
16
add(head, "That's illegal!"); // error
Copied!

Resources

Last modified 2yr ago