lezione 06

narrowing

type guards e discriminated union.

livello: intermedio durata: 22 min output: runtime safe badge: typescript essentials

type narrowing

function isString(v: unknown): v is string {
  return typeof v === "string";
}

union types

type Id = string | number;

interface

interface Project { id: number; name: string; }

function types

type Fn = (a: number, b: number) => number;
const add: Fn = (a, b) => a + b;

esercizi

definisci un type e mappa un array.

type Item = { id: number; name: string };
const items: Item[] = [{ id: 1, name: "A" }];
const names = items.map(i => i.name);
console.log(names);

panoramica

In questo capitolo su narrowing lavoriamo su type narrowing, union types, interface, function types per creare micro-pattern riutilizzabili.

lavora in sequenza: leggi, prova, modifica gli snippet e annota i trade-off principali.

badge: typescript essentials

obiettivi

  • capire e applicare type narrowing in uno scenario reale
  • capire e applicare union types in uno scenario reale
  • capire e applicare interface in uno scenario reale
  • capire e applicare function types in uno scenario reale

scheda rapida

function isString(v: unknown): v is string {
  return typeof v === "string";
}

adatta questo scheletro agli esempi della lezione.

tips

  • attiva strict
  • evita any
  • usa type alias chiari
  • separa layer e dto
  • mantieni funzioni pure
  • mantieni type narrowing leggibile

tip: documenta ogni scelta architetturale.

mini progetto

crea un array tipizzato e trasformalo.

  • definisci type
  • crea array
  • map

output atteso: output tipizzato.

checklist

  • ho eseguito gli snippet e controllato l'output
  • ho annotato almeno 2 trade-off
  • ho completato il mini progetto
  • ho salvato un riepilogo personale
start a brief