RN Lez 34: TypeScript Base
Docs: Using TypeScript
Obiettivi
Section titled “Obiettivi”- Capire i tipi base di TypeScript
- Usare type e interface
- Configurare TypeScript nel progetto
1. Setup TypeScript
Section titled “1. Setup TypeScript”# Nuovo progetto (già TS)npx create-expo-app@latest MiaApp
# Progetto esistente: basta rinominare .js in .tsxmv App.js App.tsxnpx expo start # Expo configura TS automaticamente!tsconfig.json
Section titled “tsconfig.json”{ "compilerOptions": { "strict": true, "jsx": "react-jsx", "moduleResolution": "bundler", "target": "ESNext", "module": "ESNext", "skipLibCheck": true }}
"strict": trueè la parte più importante: attiva TUTTI i controlli.
2. Tipi base
Section titled “2. Tipi base”// Tipi primitivi (sempre minuscolo!)const nome: string = 'Mario';const eta: number = 17; // interi e decimali sono numberconst isStudent: boolean = true;const nulla: null = null;
// TypeScript INFERISCE il tipo da solo:const città = 'Roma'; // string (inferito)const anno = 2026; // number (inferito)
// ❌ EVITA any! Perde i vantaggi di TSconst qualsiasi: any = 'whatever';3. Array
Section titled “3. Array”// Due sintassi equivalenti:const numeri: number[] = [1, 2, 3];const numeri2: Array<number> = [1, 2, 3]; // sintassi generics
// Array misticonst misto: (string | number)[] = ['Mario', 17];4. type e interface
Section titled “4. type e interface”// type (più comune in React)type Studente = { nome: string; eta: number; classe?: string; // ? = opzionale};
// interface (equivalente)interface Studente { nome: string; eta: number; classe?: string;}
// Usoconst studente: Studente = { nome: 'Mario', eta: 17 };
// type con unionetype Status = 'attivo' | 'inattivo' | 'sospeso';const stato: Status = 'attivo'; // OK// const stato: Status = 'boh'; // ❌ ERROREDifferenza pratica:
typesi usa di più in React per props.
5. Type inference — quando NON serve scrivere il tipo
Section titled “5. Type inference — quando NON serve scrivere il tipo”// ❌ Ridondante — TS lo sa giàconst nome: string = 'Mario';
// ✅ Meglio — lascia che TS inferiscaconst nome = 'Mario';
// ✅ Necessario — se non c'è valore inizialelet indirizzo: string;6. Tabella riassuntiva
Section titled “6. Tabella riassuntiva”| Python type hints | TypeScript |
|---|---|
nome: str | nome: string |
eta: int | eta: number |
voti: list[int] | voti: number[] |
Optional[str] | string | null |
Union[str, int] | string | number |
class Studente: | type Studente = { ... } |
7. Esercizio
Section titled “7. Esercizio”🎯 “Tipizza i dati”
Section titled “🎯 “Tipizza i dati””Crea un file types.ts con:
// 1. type Prodotto: id (number), nome (string), prezzo (number), categoria (string)// 2. type Utente: id, nome, email, eta (optional)// 3. type RispostaAPI: success (boolean), data (Prodotto[]), error (string optional)// 4. type StatoOrdine: 'in_elaborazione' | 'spedito' | 'consegnato'Poi usa questi tipi in un componente che mostra una lista di prodotti.