Advertisement

TypeScript Generics

Previous Lesson 45 of 47 Next
Advertisement
Lesson Overview: Write reusable type-safe functions and containers with generic <T> parameters.

Reusable Type Parameters

Generics let functions preserve exact input types without falling back to any. For example, function identity<T>(val: T): T keeps strings as string and numbers as number.

Generic Array Wrapper Function (Editable — type & Run)

Advertisement

Test Yourself With Exercises

Declare a generic type parameter T on function firstItem:

function firstItem (arr: T[]): T { return arr[0]; }
Advertisement