Generic Functions

Type Parameters

// T: type parameter
function firstElement<T>(arr: T[]): T {
  return arr[0];
}

// of type 'string'
const s = firstElement(["a", "b", "c"]);  // "a"
// of type 'number'
const n = firstElement([1, 2, 3]);        // 1

type parameters are for relating the types of multiple values (parameters or return value). If a type parameter is only used once in the function signature, itโ€™s not needed after all.

Type Constraints

// HasLength
interface HasLength {
  length: number;
}

// longest(a,b)
//              โ•ญโ”€โ”€ โญ๏ธ constraint โ”€โ”€โ•ฎ
function longest<T extends HasLength>(a: T, b: T) {
  return (a.length >= b.length) ? a : b;
}
 
// of type 'number[]'
const a1 = longest([1, 2], [1, 2, 3]);    // [1, 2, 3]

// of type 'alice' | 'bob'
const a2 = longest("alice", "bob");       // "alice"

Last updated