Lesson 10 of 15

Generics

Generics

A generic function works with any type, while still being type-safe. Use <T> to declare a type parameter:

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

console.log(identity("hello"));  // string
console.log(identity(42));       // number
console.log(identity(true));     // boolean

TypeScript infers T from the argument — no need to specify it manually.

Generic Arrays

function first<T>(arr: T[]): T | undefined {
    return arr[0];
}

console.log(first([1, 2, 3]));        // 1
console.log(first(["a", "b", "c"]));  // a
console.log(first([]));               // undefined

Multiple Type Parameters

function pair<A, B>(a: A, b: B): [A, B] {
    return [a, b];
}

const p = pair("Alice", 30);   // [string, number]

Why Generics?

Without generics, you would use any, which loses all type information. Generics preserve the relationship between input and output types.

Your Task

Write function last<T>(arr: T[]): T | undefined that returns the last element of an array, or undefined if the array is empty.

TypeScript loading...
Loading...
Click "Run" to execute your code.