Emmanuel Akinfulubi

TypeScriptAdvanced types

Generic identity function in TypeScript

9 A generic function that hands back what it was given

easy

Write a function that accepts a value of any type and returns the same value, keeping its type intact. Try it with several different types and show that the type survives.

Stuck? Three hints, smallest first
  1. 1. The type parameter goes in angle brackets: function identity<T>(value: T): T.
  2. 2. With any the type is lost. With <T> the caller’s type comes out the other end.
  3. 3. You almost never pass T explicitly. TypeScript works it out from the argument.

The answer, and proof it works

const same = (a: unknown, b: unknown): boolean =>
  JSON.stringify(a) === JSON.stringify(b);

function test(name: string, got: unknown, want: unknown): void {
  console.log(
    (same(got, want) ? 'ok   ' : 'FAIL ') + name +
    (same(got, want) ? '' : `  got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
  );
}

function identity<T>(value: T): T {
  return value;
}

// The type survives, so type-specific methods are available afterwards.
const text = identity('Lagos');          // string
const count = identity(42);              // number
const flag = identity(true);             // boolean
const list = identity([1, 2, 3]);        // number[]
const shape = identity({ plate: 'LAG-441-XA' });

console.log(text.toUpperCase());         // allowed: it is a string
console.log(count.toFixed(1));           // allowed: it is a number
console.log(list.map((n) => n * 2));     // allowed: it is number[]
console.log(shape.plate);

// Compare with the any version, which throws the type away.
function identityAny(value: any): any { return value; }
const lost = identityAny('Lagos');
// lost.anythingAtAll() would compile. That is the problem.

test('text survived as text', text.toUpperCase(), 'LAGOS');
test('number survived as number', count.toFixed(1), '42.0');
test('boolean survived', flag, true);
test('array survived with its element type', list.map((n) => n * 2), [2, 4, 6]);
test('object shape survived', shape.plate, 'LAG-441-XA');
test('the any version still returns the value', lost, 'Lagos');

Output


      

identity looks pointless and is the clearest possible illustration of what a type parameter is: a placeholder the caller fills in. Compare the last block. any also returns the value, but the returned type is any, so every method call on it is unchecked from then on.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.