Skip to content

RN Lez 34: TypeScript Base

Docs: Using TypeScript

  • Capire i tipi base di TypeScript
  • Usare type e interface
  • Configurare TypeScript nel progetto

Terminal window
# Nuovo progetto (già TS)
npx create-expo-app@latest MiaApp
# Progetto esistente: basta rinominare .js in .tsx
mv App.js App.tsx
npx expo start # Expo configura TS automaticamente!
{
"compilerOptions": {
"strict": true,
"jsx": "react-jsx",
"moduleResolution": "bundler",
"target": "ESNext",
"module": "ESNext",
"skipLibCheck": true
}
}

"strict": true è la parte più importante: attiva TUTTI i controlli.


// Tipi primitivi (sempre minuscolo!)
const nome: string = 'Mario';
const eta: number = 17; // interi e decimali sono number
const 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 TS
const qualsiasi: any = 'whatever';

// Due sintassi equivalenti:
const numeri: number[] = [1, 2, 3];
const numeri2: Array<number> = [1, 2, 3]; // sintassi generics
// Array misti
const misto: (string | number)[] = ['Mario', 17];

// type (più comune in React)
type Studente = {
nome: string;
eta: number;
classe?: string; // ? = opzionale
};
// interface (equivalente)
interface Studente {
nome: string;
eta: number;
classe?: string;
}
// Uso
const studente: Studente = { nome: 'Mario', eta: 17 };
// type con unione
type Status = 'attivo' | 'inattivo' | 'sospeso';
const stato: Status = 'attivo'; // OK
// const stato: Status = 'boh'; // ❌ ERRORE

Differenza pratica: type si 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 inferisca
const nome = 'Mario';
// ✅ Necessario — se non c'è valore iniziale
let indirizzo: string;

Python type hintsTypeScript
nome: strnome: string
eta: inteta: number
voti: list[int]voti: number[]
Optional[str]string | null
Union[str, int]string | number
class Studente:type Studente = { ... }

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.