Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials TypeScript Generic Functions
TypeScript Intermediate FREE

Generic Functions

Lesson 1 of 17 Intermediate Interactive

Generics create reusable components that work with multiple types.

Syntax

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

const num = identity<number>(42);
const str = identity<string>("hello");
Generic Functions
TYPESCRIPT
function identity<T>(value: T): T {
    return value;
}

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

console.log(identity<string>("hello"));
console.log(identity<number>(42));

let nums = [1, 2, 3];
console.log(getFirst(nums));