Skip to content

TypeScript per principianti: perché dovresti impararlo

TypeScript sta diventando lo standard per lo sviluppo JavaScript su larga scala. Ecco perché dovresti impararlo.

Cos'è TypeScript?

TypeScript è un superset di JavaScript che aggiunge tipizzazione statica opzionale:

typescript
// JavaScript
function somma(a, b) {
  return a + b;
}

// TypeScript
function somma(a: number, b: number): number {
  return a + b;
}

Vantaggi principali

1. Type safety

typescript
interface User {
  id: number;
  name: string;
  email: string;
}

function getUser(id: number): User {
  // ...fetch from API
  return { id, name: 'Mario', email: '[email protected]' };
}

2. Autocompletamento migliore

Gli IDE possono offrire suggerimenti più accurati grazie ai tipi.

3. Refactoring sicuro

TypeScript ti avvisa se cambi l'interfaccia di una funzione.

Installazione

bash
npm install -g typescript
tsc --init

Configurazione base (tsconfig.json)

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true,
    "outDir": "./dist",
    "rootDir": "./src"
  }
}

Tipi fondamentali

typescript
// Tipi primitivi
let nome: string = 'Mario';
let eta: number = 30;
let attivo: boolean = true;

// Array
let numeri: number[] = [1, 2, 3];
let nomi: Array<string> = ['Mario', 'Luigi'];

// Union types
let id: string | number = 'abc';
id = 123; // OK

// Type aliases
type Point = {
  x: number;
  y: number;
};

// Interfaces
interface User {
  id: number;
  name: string;
  email?: string; // opzionale
}

Conclusione

TypeScript migliora la developer experience e riduce i bug runtime. La curva di apprendimento è ripida all'inizio, ma i benefici sono enormi per progetti di qualsiasi dimensione.

Made with ❤️ by PeterDev
'Ho mio cuGGGino che lo sa fare' cit.