Generics
Generics let one function, interface, or class work with multiple types safely.
function identity<T>(value: T): T {
return value;
}
Generic Arrays
function getFirstItem<T>(items: T[]): T {
return items[0];
}
Union Types
let result: string | number;
result = "Pass";
result = 90;
Literal Types
type Direction = "left" | "right" | "up" | "down";
Intersection Types
type Person = { name: string };
type Worker = { company: string };
type Employee = Person & Worker;
Optional Chaining and Nullish Coalescing
console.log(user.contact?.email);
let finalValue = inputValue ?? "Default Text";
Best practice: Use advanced types when they make the code clearer and more reusable, not just because they are available.
Summary
Generics and advanced types make TypeScript especially powerful for building flexible and scalable applications while preserving safety.