- 01Getting Started
- 02Your First Output (console.log)
- 03Variables and Type Annotations (number/string/boolean)
- 04Array Types
- 05Function Types (Parameters and Return Values)
- 06Optional Parameters and Default Parameters
- 07Interfaces (interface)
- 08Optional Properties (?)
- 09Type Aliases (type)
- 10Union Types
- 11Literal Types
- 12enum (Enumerated Types)
- 13Classes and Types
- 14Inheritance (extends) and Implementing an Interface (implements)
- 15Generics (<T>)
- 16Tuple Types
- 17The any and unknown Types
- 18Type Assertions (as)
- 19The readonly Modifier
- 20[Applied] Build a Mini Inventory Management System
Generics (<T>)
This lesson covers generics (<T>), which let you build functions and types that work with a variety of different types. It's for anyone searching "TypeScript generics usage."
Generics are like a "type variable" whose actual type gets decided later. You declare a placeholder type with the symbol <T>, and fill in the concrete type (number, string, and so on) when it's actually used.
The example defines function firstItem<T>(arr: T[]): T. This function works with both a number array and a string array, and returns a correctly-typed value each time.
A common early mistake is asking "why not just use any?" Using any disables type checking entirely, whereas generics preserve type safety while keeping the relationship "the type returned matches the type of the array you passed in."
In real projects, generics are used heavily wherever "the types differ, but the flow of logic is the same" โ array-processing utility functions, or common API-communication logic.
๐งช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ nothing is sent anywhere).
