lezione 03

funzioni e generics

funzioni tipizzate e generics.

livello: intermedio durata: 24 min output: api type-safe badge: typescript essentials

function types

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

generics

function wrap<T>(value: T): T[] { return [value]; }

tipi base

let year: number = 2026;
let name: string = "Samir";

union types

type Id = string | number;

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 funzioni e generics lavoriamo su function types, generics, tipi base, union 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 function types in uno scenario reale
  • capire e applicare generics in uno scenario reale
  • capire e applicare tipi base in uno scenario reale
  • capire e applicare union types in uno scenario reale

scheda rapida

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

adatta questo scheletro agli esempi della lezione.

tips

  • attiva strict
  • evita any
  • usa type alias chiari
  • separa layer e dto
  • mantieni funzioni pure
  • mantieni function types 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