Capitolo 5: Il sistema dei tipi – dalle basi agli avanzati

  



Questo è il capitolo che ti farà davvero capire la potenza di TypeScript. Iniziamo con i tipi primitivi, poi passiamo a tipi complessi, unioni, generici, type inference, narrowing e altro ancora.

🔗 Ti piace Techelopment? Dai un’occhiata al sito per tutti i dettagli!

🧱 1. Tipi primitivi

Questi sono i tipi base, comuni a molti linguaggi:

let name: string = "Angelina";
let age: number = 28;
let active: boolean = true;
let nothing: null = null;
let unknow: undefined = undefined;

🔹 string, number, boolean, null, undefined, bigint, symbol

Se non li specifichi, TypeScript cerca di inferirli automaticamente:

let surname = "Jolie"; // TS understands that it is a string

🧩 2. Array e Tuple

Array:

let numbers: number[] = [1, 2, 3];
let names: Array = ["Angelina", "Cameron"];

💡 3. Type inference (inferenza dei tipi)

TypeScript deduce i tipi anche se non li scrivi:

let message = "hello"; // it is string
let x = [1, 2, 3];// it is number[]

Se però serve più controllo o chiarezza, è buona pratica specificarli esplicitamente.


🚧 4. Type alias e Interfacce

Alias:

type ID = string | number;

let userId: ID = 123;
userId = "abc123";

Interfacce:

interface Person {
  name: string;
  age: number;
  active?: boolean; // optional
}

Differenza?
👉 type può descrivere unione, tuple, primitive ecc.
👉 interface è pensata per oggetti e classi.


⚙️ 5. Funzioni tipizzate

function sum(a: number, b: number): number {
  return a + b;
}

Puoi anche tipizzare funzioni anonime o di callback:

const multiply: (x: number, y: number) => number = (x, y) => x * y;

🔗 6. Tipi unione (|) e intersezione (&)

Unione:

let input: string | number;
input = "hello";
input = 42;

Intersezione:

type A = { name: string };
type B = { age: number };

type PersonComplete = A & B;

const user: PersonComplete = { name: "Carrie", age: 30 };

🔍 7. Type narrowing (raffinamento dei tipi)

Quando un valore può avere più tipi, TypeScript ti aiuta a “capire” il tipo effettivo in un certo punto del codice:

function print(val: string | number) {
  if (typeof val === "string") {
    console.log(val.toUpperCase()); // it is a stringa!
  } else {
    console.log(val.toFixed(2)); // it is a number!
  }
}

Anche instanceof, in e Array.isArray() sono strumenti di narrowing.


🧠 8. Tipi generici (generics)

I generics permettono di scrivere codice riutilizzabile e flessibile:

function myElements<T>(list: T[]): T {
  return list[0];
}

const s = myElements(["a", "b"]); // T = string
const n = myElements([1, 2, 3]); // T = number

Puoi usarli con classi, interfacce e tipi personalizzati.


🧱 9. Tipi literal e enum

Literal types:

let direction: "up" | "down" | "left" | "right";
direction = "up"; // ok
direction = "in front"; // error

Enum:

enum Color {
  Red,
  Green,
  Blue,
}

let c: Color = Color.Red;

🧪 10. Tipi avanzati utili

TipoDescrizione
anyDisattiva ogni controllo (da evitare)
unknownCome any, ma richiede type-check prima dell’uso
neverFunzione che non ritorna mai (es. throw)
voidNessun valore di ritorno
Record<K, V>Oggetto generico con chiavi K e valori V
Partial<T>Rende tutte le proprietà di T opzionali
Readonly<T>Rende tutte le proprietà di T immutabili

Esempio con Record:

const translations: Record<string, string> = {
  it: "Ciao",
  en: "Hello",
  es: "Hola",
};

🎯 In sintesi

TypeScript ti offre un sistema di tipi:

  • ✅ Statico ma opzionale

  • ✅ Estremamente flessibile e potente

  • ✅ Che ti aiuta a prevenire errori, documentare il codice e costruire API solide


 

Follow me #techelopment

Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment