...

/

Inferring Generics

Inferring Generics

Learn how TypeScript simplifies generic type inference.

We'll cover the following...

TypeScript is always trying to get out of our way. If it can figure out what a generic ought to be, it will relieve us of the responsibility of telling it. Let’s take a look at the following code:

TypeScript 4.9.5
export const identity = <T>(x: T): T => {
return x;
};
export const foo = identity<string>('foo');
export const two = identity(2);
console.log(foo);
console.log(two);

In the code above, we’re able to completely omit telling TypeScript what type T should be. It seems that we’re handing that function call a number, so it’s able to figure out that T is a number in this case.

We can also leverage this to simplify our linked list above:

TypeScript 4.9.5
type LinkedListNode<T> = {
value: T;
next?: LinkedListNode<T>;
};
const createLinkedListNode = <T>(value: T): LinkedListNode<T> => {
return { value };
};
const firstNode = createLinkedListNode('first');
const secondNode = createLinkedListNode('second');
firstNode.next = secondNode;
console.log(firstNode);

Let’s explain the code sample above:

  • Lines 6–8: We define a generic function named createLinkedListNode that receive a value as a parameter, and return the linked list node with that value.

  • Lines 10–12: We create two linked list nodes and name them firstNode and secondNode by calling the createLinkedListNode ...