Generics create reusable components that work with multiple types.
Getting Started
What is TypeScript?
Basic Types
Types & Interfaces
Async TypeScript
Promises & Async/Await
TypeScript
Intermediate
FREE
Generic Functions
Lesson 1 of 17
Intermediate
Interactive
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));