TypeScript Generics
Scrivi codice flessibile E type-safe: una funzione, infiniti tipi. La chiave per librerie e API robuste.
TypeScript Generics
🎯 Cos'è in Parole Semplici?
Immagina una scatola. Può contenere qualsiasi cosa: scarpe, libri, cibo. Ma una volta che ci metti qualcosa, "diventa" una scatola di quel tipo.
typescript
// Senza generics: perdi l'informazione del tipo
function getFirst(arr: any[]): any {
return arr[0];
}
const x = getFirst([1, 2, 3]); // x è 'any' 😕
// Con generics: mantieni il tipo!
function getFirst<T>(arr: T[]): T {
return arr[0];
}
const x = getFirst([1, 2, 3]); // x è 'number' 🎉I generics sono variabili per i tipi: definisci la struttura una volta, usi con qualsiasi tipo.
📝 Sintassi Base
Funzioni Generiche
typescript
// T è la variabile di tipo (convenzione: T, U, K, V)
function identity<T>(value: T): T {
return value;
}
// Uso esplicito
const a = identity<string>("hello"); // a: string
// Uso con inferenza (TypeScript capisce da solo)
const b = identity(42); // b: numberInterfacce Generiche
typescript
interface Box<T> {
content: T;
label: string;
}
const numberBox: Box<number> = { content: 42, label: "Answer" };
const stringBox: Box<string> = { content: "Hi", label: "Greeting" };Classi Generiche
typescript
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
}
const numberStack = new Stack<number>();
numberStack.push(1);
numberStack.push(2);🔒 Constraints (Vincoli)
Problema
typescript
function getLength<T>(item: T): number {
return item.length; // ❌ Errore! T potrebbe non avere .length
}Soluzione: extends
typescript
// T DEVE avere una proprietà length
interface HasLength {
length: number;
}
function getLength<T extends HasLength>(item: T): number {
return item.length; // ✅ Ora TypeScript sa che esiste
}
getLength("hello"); // ✅ string ha length
getLength([1, 2, 3]); // ✅ array ha length
getLength({ length: 5 }); // ✅ oggetto con length
getLength(123); // ❌ number non ha lengthConstraint con keyof
typescript
// K deve essere una chiave esistente di T
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: "Alice", age: 30 };
getProperty(user, "name"); // ✅ "Alice", tipo string
getProperty(user, "age"); // ✅ 30, tipo number
getProperty(user, "email"); // ❌ Errore! "email" non esiste in user🧰 Utility Types Built-in
TypeScript include generics già pronti:
| Utility | Cosa Fa | Esempio |
|---|---|---|
Partial<T> | Rende tutto opzionale | Form con campi parziali |
Required<T> | Rende tutto obbligatorio | Validazione finale |
Readonly<T> | Rende tutto immutabile | Stato Redux |
Pick<T, K> | Prende solo alcune chiavi | Subset di un oggetto |
Omit<T, K> | Esclude alcune chiavi | Rimuovi campi sensibili |
Record<K, V> | Mappa chiavi a valori | Dizionari tipizzati |
ReturnType<F> | Tipo di ritorno di funzione | Inferire tipi |
Parameters<F> | Tipi dei parametri | Clone di funzione |
Esempi Pratici
typescript
interface User {
id: number;
name: string;
email: string;
password: string;
}
// Per update: tutto opzionale
type UserUpdate = Partial<User>;
// { id?: number; name?: string; email?: string; password?: string }
// Per API response: senza password
type PublicUser = Omit<User, "password">;
// { id: number; name: string; email: string }
// Solo credenziali
type Credentials = Pick<User, "email" | "password">;
// { email: string; password: string }
// Mappa ID -> User
type UsersById = Record<number, User>;
// { [id: number]: User }🎣 Default Types
typescript
// T di default è string se non specificato
interface Container<T = string> {
value: T;
}
const a: Container = { value: "hello" }; // T = string
const b: Container<number> = { value: 42 }; // T = number💡 Pattern Comuni
1. API Response Wrapper
typescript
interface ApiResponse<T> {
data: T;
status: number;
message: string;
timestamp: Date;
}
async function fetchUser(id: number): Promise<ApiResponse<User>> {
// ...
}
// Il tipo di data è automaticamente User
const response = await fetchUser(1);
console.log(response.data.name); // Type-safe!2. Factory Function
typescript
function createState<T>(initial: T) {
let value = initial;
return {
get: () => value,
set: (newValue: T) => { value = newValue; }
};
}
const counter = createState(0); // number
const name = createState("Alice"); // string3. Event Handler
typescript
type EventHandler<T> = (event: T) => void;
interface ClickEvent { x: number; y: number; }
interface KeyEvent { key: string; code: number; }
const handleClick: EventHandler<ClickEvent> = (e) => {
console.log(e.x, e.y); // Type-safe
};⚠️ Errori Comuni
- Usare
anyinvece di generics → Perdi type safety - Troppi parametri generici → Codice illeggibile
- Dimenticare constraints → Errori a runtime
- Non sfruttare l'inferenza → Codice verboso inutilmente
javascript
// ============================================
// ESEMPI PRATICI TYPESCRIPT GENERICS
// ============================================
// 📦 1. GENERIC API CLIENT
// ============================================
class ApiClient {
private baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
// GET generico - il tipo di ritorno è quello che specifichi
async get<T>(endpoint: string): Promise<T> {
const response = await fetch(`${this.baseUrl}${endpoint}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json() as Promise<T>;
}
// POST generico - specifichi tipo input E output
async post<TBody, TResponse>(endpoint: string, data: TBody): Promise<TResponse> {
const response = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
return response.json() as Promise<TResponse>;
}
}
// Uso type-safe
interface User { id: number; name: string; email: string; }
interface CreateUserDTO { name: string; email: string; }
const api = new ApiClient('https://api.example.com');
const user = await api.get<User>('/users/1');
console.log(user.name); // ✅ TypeScript sa che è string
const newUser = await api.post<CreateUserDTO, User>(
'/users',
{ name: 'Alice', email: 'alice@example.com' }
);
// 🎨 2. REACT COMPONENT GENERICO
// ============================================
interface SelectProps<T> {
items: T[];
value: T | null;
onChange: (item: T) => void;
getLabel: (item: T) => string;
getValue: (item: T) => string | number;
}
function Select<T>({ items, value, onChange, getLabel, getValue }: SelectProps<T>) {
return (
<select
value={value ? getValue(value) : ''}
onChange={(e) => {
const selected = items.find(item =>
String(getValue(item)) === e.target.value
);
if (selected) onChange(selected);
}}
>
{items.map(item => (
<option key={getValue(item)} value={getValue(item)}>
{getLabel(item)}
</option>
))}
</select>
);
}
// Uso con diversi tipi
interface Country { code: string; name: string; }
const countries: Country[] = [{ code: 'IT', name: 'Italia' }, { code: 'FR', name: 'Francia' }];
<Select<Country>
items={countries}
value={selectedCountry}
onChange={setSelectedCountry}
getLabel={(c) => c.name}
getValue={(c) => c.code}
/>
// 🗄️ 3. STORAGE GENERICO TYPE-SAFE
// ============================================
class TypedStorage<T extends Record<string, unknown>> {
constructor(private prefix: string) {}
set<K extends keyof T>(key: K, value: T[K]): void {
localStorage.setItem(
`${this.prefix}_${String(key)}`,
JSON.stringify(value)
);
}
get<K extends keyof T>(key: K): T[K] | null {
const item = localStorage.getItem(`${this.prefix}_${String(key)}`);
return item ? JSON.parse(item) : null;
}
}
// Definisci lo schema
interface AppSettings {
theme: 'light' | 'dark';
language: string;
notifications: boolean;
}
const settings = new TypedStorage<AppSettings>('app');
settings.set('theme', 'dark'); // ✅
settings.set('theme', 'invalid'); // ❌ Errore!
settings.set('language', 'it'); // ✅
settings.set('nonExistent', 'x'); // ❌ Errore!
const theme = settings.get('theme'); // tipo: 'light' | 'dark' | null
// 🔧 4. UTILITY TYPE CUSTOM
// ============================================
// Rende solo alcuni campi opzionali
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
interface Article {
id: number;
title: string;
content: string;
author: string;
createdAt: Date;
}
// Per creare: id e createdAt sono generati dal server
type CreateArticle = PartialBy<Article, 'id' | 'createdAt'>;
// { title: string; content: string; author: string; id?: number; createdAt?: Date }