Hone

Lessons · TypeScript · generics

A function that keeps the type it was given

function first<T>(xs: T[]): T uses a placeholder T that is filled in from the argument each call.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Utility functions (first, last, groupBy, pick) work on any type; generics let them do that without losing the type on the way out.

How to think about it

Am I writing the same function for two types? If you find yourself writing the same function for number[] and string[], introduce <T>. Name it by what it is (TItem) when there is more than one.

Worked example

function last<T>(xs: T[]): T | undefined { return xs[xs.length - 1]; }
T is whatever the array holds; the result is one of those, or undefined when empty.
const n = last([1, 2]);
n is number | undefined.
const s = last(["a"]);
s is string | undefined. Same function, right type each time.

Your turn

Make wrap generic.

function wrap<>(x: T): T[] { return [x]; }

The trap

Using any where a generic belongs. any loses the type; T carries it through.

Practise generics on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.