Pompei Tech
Guide · typescript

Classi

Classi

Pensa alla catena di montaggio di una fabbrica di automobili. Ogni auto che esce dalla linea ha un numero di matricola progressivo — ma quel numero non lo decide l'auto stessa, lo assegna un contatore condiviso da tutta la fabbrica, che tiene traccia di quante unità sono state prodotte finora. Alcune informazioni, poi, sono visibili a chiunque entri in salone (il colore, il modello), altre sono riservate al reparto tecnico (il numero di telaio), altre ancora sono scritte su un foglio che nessuno, a parte l'operaio che lo ha compilato, dovrebbe mai leggere.

Le classi TypeScript aggiungono funzionalità potenti e importanti sopra le classi JavaScript tradizionali, e questa distinzione — cosa è condiviso tra tutte le istanze, cosa è pubblico, cosa è riservato — è al centro del capitolo. Diamo un'occhiata da vicino ai campi di classe, alle keyword di visibilità e altro ancora!

Campi e metodi

Torniamo al nostro esempio dell'auto. Nel mondo JS, potremmo avere qualcosa come:

js
////////////////////////////////
// JavaScript, non TypeScript //
////////////////////////////////
class Auto {
  constructor(marca, modello, anno) {
    this.marca = marca;
    this.modello = modello;
    this.anno = anno;
  }
}

let berlina = new Auto("Honda", "Accord", 2017);
berlina.attivaFrecce("sinistra"); // non sicuro!
new Auto(2017, "Honda", "Accord"); // non sicuro!

Se ci fermiamo un attimo a pensare, questo è permesso nel mondo JS perché ogni valore, incluse le proprietà della classe e le istanze della classe stessa, è di fatto di tipo any.

Nel mondo TypeScript, vogliamo avere qualche garanzia che verremo fermati a compile time se proviamo a invocare il metodo inesistente attivaFrecce sulla nostra auto. Per ottenerla, dobbiamo fornire qualche informazione in più fin da subito:

ts
class class AutoAuto {
  Auto.marca: stringmarca: string;
  Auto.modello: stringmodello: string;
  Auto.anno: numberanno: number;
  constructor(marca: stringmarca: string, modello: stringmodello: string, anno: numberanno: number) {
    this.Auto.marca: stringmarca = marca: stringmarca;
    this.Auto.modello: stringmodello = modello: stringmodello;
    this.Auto.anno: numberanno = anno: numberanno;
  }
}

let let berlina: Autoberlina = new constructor Auto(marca: string, modello: string, anno: number): AutoAuto("Honda", "Accord", 2017);
let berlina: Autoberlina.attivaFrecce("sinistra");
Property 'attivaFrecce' does not exist on type 'Auto'.
new constructor Auto(marca: string, modello: string, anno: number): AutoAuto(2017, "Honda", "Accord");
Argument of type 'number' is not assignable to parameter of type 'string'.

Due cose da notare nello snippet sopra:

  • Stiamo dichiarando i tipi di ogni campo della classe.
  • Stiamo dichiarando i tipi di ogni argomento del costruttore.

Questa sintassi comincia a diventare un po' verbosa — per esempio, le parole "marca", "modello" e "anno" sono scritte in quattro punti diversi ciascuna. Come vedremo più avanti, TypeScript ha un modo più conciso di scrivere codice come questo.

Esprimere i tipi per i metodi di classe funziona seguendo in gran parte lo stesso pattern usato per gli argomenti e i valori di ritorno delle funzioni:

ts
class class AutoAuto {
  Auto.marca: stringmarca: string;
  Auto.modello: stringmodello: string;
  Auto.anno: numberanno: number;
  constructor(marca: stringmarca: string, modello: stringmodello: string, anno: numberanno: number) {
    this.Auto.marca: stringmarca = marca: stringmarca;
    this.Auto.modello: stringmodello = modello: stringmodello;
    this.Auto.anno: numberanno = anno: numberanno;
  }
  Auto.clacson(durata: number): stringclacson(durata: numberdurata: number): string {
    return `t${"u".String.repeat(count: number): string
Returns a String value that is made from count copies appended together. If count is 0, the empty string is returned.
@paramcount number of copies to append
repeat
(durata: numberdurata)}t`;
} } const const c: Autoc = new constructor Auto(marca: string, modello: string, anno: number): AutoAuto("Honda", "Accord", 2017); const c: Autoc.
Auto.clacson(durata: number): string
clacson
(5);

Campi, metodi e blocchi static

A volte è utile avere campi e metodi sulla classe, invece che sulla istanza di quella classe — esattamente come il contatore di matricole condiviso da tutta la fabbrica, e non da ogni singola auto. Le aggiunte recenti a JavaScript e TypeScript rendono questo possibile!

Il modo per indicare che un campo o un metodo dovrebbe essere trattato così è tramite la keyword static.

Ecco un esempio in cui vogliamo avere un contatore che si incrementa a ogni nuova istanza:

ts
class class AutoAuto {
  // Roba statica (condivisa da tutta la "fabbrica")
  static Auto.prossimaMatricola: numberprossimaMatricola = 100;
  static Auto.generaMatricola(): numbergeneraMatricola() {
    return this.Auto.prossimaMatricola: numberprossimaMatricola++;
  }

  // Roba di istanza (specifica per ogni singola auto)
  Auto.marca: stringmarca: string;
  Auto.modello: stringmodello: string;
  Auto.anno: numberanno: number;
  Auto.matricola: numbermatricola = class AutoAuto.Auto.generaMatricola(): numbergeneraMatricola();
  constructor(marca: stringmarca: string, modello: stringmodello: string, anno: numberanno: number) {
    this.Auto.marca: stringmarca = marca: stringmarca;
    this.Auto.modello: stringmodello = modello: stringmodello;
    this.Auto.anno: numberanno = anno: numberanno;
  }
  Auto.getEtichetta(): stringgetEtichetta() {
    return `${this.Auto.marca: stringmarca} ${this.Auto.modello: stringmodello} ${this.Auto.anno: numberanno} - #${this.Auto.matricola: numbermatricola}`;
  }
}
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(new constructor Auto(marca: string, modello: string, anno: number): AutoAuto("Honda", "Accord", 2017).Auto.getEtichetta(): stringgetEtichetta());
// > "Honda Accord 2017 - #100" var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(new constructor Auto(marca: string, modello: string, anno: number): AutoAuto("Toyota", "Camry", 2022).Auto.getEtichetta(): stringgetEtichetta());
// > "Toyota Camry 2022 - #101"

A meno che tu non dica diversamente, i campi statici sono accessibili da ovunque la classe Auto sia accessibile (sia dall'interno che dall'esterno della classe). Se questo è indesiderato, TypeScript ci fornisce le keyword di visibilità e dei veri campi privati (#campo), di cui parleremo entrambi qui sotto.

C'è un altro posto in cui compare il mondo static: accanto a un blocco di codice. Immaginiamo di non voler far partire il contatore delle matricole da 100, ma di volerlo caricare da un'API esterna.

ts
class class AutoAuto {
  // Roba statica
  static Auto.prossimaMatricola: numberprossimaMatricola: number;
  static Auto.generaMatricola(): numbergeneraMatricola() {
    return this.Auto.prossimaMatricola: numberprossimaMatricola++;
  }
  static {
    // "this" qui è lo scope statico
    function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch)
fetch
("https://api.example.com/dati_matricole")
.Promise<Response>.then<any, never>(onfulfilled?: ((value: Response) => any) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<any>
Attaches callbacks for the resolution and/or rejection of the Promise.
@paramonfulfilled The callback to execute when the Promise is resolved.@paramonrejected The callback to execute when the Promise is rejected.@returnsA Promise for the completion of which ever callback is executed.
then
((response: Responseresponse) => response: Responseresponse.Body.json(): Promise<any>
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json)
json
())
.Promise<any>.then<void, never>(onfulfilled?: ((value: any) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>
Attaches callbacks for the resolution and/or rejection of the Promise.
@paramonfulfilled The callback to execute when the Promise is resolved.@paramonrejected The callback to execute when the Promise is rejected.@returnsA Promise for the completion of which ever callback is executed.
then
((data: anydata) => {
this.Auto.prossimaMatricola: numberprossimaMatricola = data: anydata.ultimaMatricolaUsata + 1; }); } // Roba di istanza Auto.marca: stringmarca: string; Auto.modello: stringmodello: string; Auto.anno: numberanno: number; Auto.matricola: numbermatricola = class AutoAuto.Auto.generaMatricola(): numbergeneraMatricola(); constructor(marca: stringmarca: string, modello: stringmodello: string, anno: numberanno: number) { this.Auto.marca: stringmarca = marca: stringmarca; this.Auto.modello: stringmodello = modello: stringmodello; this.Auto.anno: numberanno = anno: numberanno; } }

Questo blocco static viene eseguito durante l'inizializzazione della classe, cioè nel momento in cui viene valutata la dichiarazione class stessa (da non confondere con la creazione di un'istanza). Ti starai chiedendo quale sia la differenza tra questo e l'esecuzione di una logica simile a livello di modulo, fuori dalla classe. Stiamo per parlare di come rendere i campi privati, e i blocchi static hanno accesso agli scope privati.

Questa funzionalità del linguaggio permette persino di creare qualcosa di simile a quello che fa la keyword friend in C++ — dare a un'altra classe dichiarata nello stesso scope l'accesso ai dati privati.

Keyword di visibilità

public, private e protected

TypeScript fornisce tre keyword di visibilità, che possono essere usate con campi e metodi di classe, per descrivere chi dovrebbe poter vedere e usare quel campo o quel metodo.

keywordchi può accedere (campo/metodo di istanza)
publicChiunque abbia accesso allo scope in cui esiste l'istanza
protectedL'istanza stessa, e le sue sottoclassi
privateSolo l'istanza stessa

Vediamo come funziona nel contesto di un esempio — il nostro "numero di telaio", visibile solo al reparto tecnico:

ts
class class AutoAuto {
  // Roba statica
  static Auto.prossimaMatricola: numberprossimaMatricola: number;
  static Auto.generaMatricola(): numbergeneraMatricola() {
    return this.Auto.prossimaMatricola: numberprossimaMatricola++;
  }
  static {
    function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> (+1 overload)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch)
fetch
("https://api.example.com/dati_matricole")
.Promise<Response>.then<any, never>(onfulfilled?: ((value: Response) => any) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<any>
Attaches callbacks for the resolution and/or rejection of the Promise.
@paramonfulfilled The callback to execute when the Promise is resolved.@paramonrejected The callback to execute when the Promise is rejected.@returnsA Promise for the completion of which ever callback is executed.
then
((response: Responseresponse) => response: Responseresponse.Body.json(): Promise<any>
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json)
json
())
.Promise<any>.then<void, never>(onfulfilled?: ((value: any) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>
Attaches callbacks for the resolution and/or rejection of the Promise.
@paramonfulfilled The callback to execute when the Promise is resolved.@paramonrejected The callback to execute when the Promise is rejected.@returnsA Promise for the completion of which ever callback is executed.
then
((data: anydata) => {
this.Auto.prossimaMatricola: numberprossimaMatricola = data: anydata.ultimaMatricolaUsata + 1; }); } // Roba di istanza Auto.marca: stringmarca: string; Auto.modello: stringmodello: string; Auto.anno: numberanno: number; private Auto._matricola: number_matricola = class AutoAuto.Auto.generaMatricola(): numbergeneraMatricola(); protected get Auto.matricola: numbermatricola() { return this.Auto._matricola: number_matricola; } constructor(marca: stringmarca: string, modello: stringmodello: string, anno: numberanno: number) { this.Auto.marca: stringmarca = marca: stringmarca; this.Auto.modello: stringmodello = modello: stringmodello; this.Auto.anno: numberanno = anno: numberanno; } } class class BerlinaBerlina extends class AutoAuto {
Berlina.getInfoBerlina(): {
    marca: string;
    modello: string;
    anno: number;
    matricola: number;
}
getInfoBerlina
() {
this._matricola;
Property '_matricola' is private and only accessible within class 'Auto'.
const { const marca: stringmarca, const modello: stringmodello, const anno: numberanno, const matricola: numbermatricola } = this; return { marca: stringmarca, modello: stringmodello, anno: numberanno, matricola: numbermatricola }; } } const const b: Berlinab = new constructor Berlina(marca: string, modello: string, anno: number): BerlinaBerlina("Nissan", "Altima", 2020); const b: Berlinab.matricola;
Property 'matricola' is protected and only accessible within class 'Auto' and its subclasses.

Un paio di cose da notare nell'esempio sopra:

  • Lo scope più esterno non ha più la possibilità di leggere matricola (né direttamente _matricola).
  • Berlina non ha accesso diretto in scrittura a _matricola, ma può leggerlo attraverso il getter protetto matricola.
  • Auto può esporre funzionalità private definendo una propria funzionalità protected (il getter matricola).
  • Berlina può esporre funzionalità protected definendo una propria funzionalità public (il valore di ritorno di getInfoBerlina()).

Queste keyword di visibilità possono essere usate anche con campi e metodi static:

keywordchi può accedere (campo/metodo statico)
publicChiunque abbia accesso allo scope in cui esiste la classe
protectedGli scope statici e di istanza della classe e delle sue sottoclassi
privateSolo lo scope statico e di istanza della classe stessa

:::warning Non serve a mantenere segreti o per la sicurezza È importante capire che, come ogni altro aspetto delle informazioni di tipo, le keyword di visibilità vengono validate solo a compile time, senza alcun reale beneficio di privacy o sicurezza a runtime. Questo significa che, anche se marchiamo qualcosa come private, se un utente decide di mettere un breakpoint e ispezionare il codice in esecuzione a runtime, potrà comunque vedere tutto. :::

Campi privati # nativi di JS

Dalla versione 3.8, TypeScript supporta l'uso dei campi privati nativi di ECMAScript. Se hai problemi a farli funzionare nel tuo codebase, controlla bene la configurazione di Babel.

ts
class class AutoAuto {
  private static Auto.prossimaMatricola: numberprossimaMatricola: number;
  private static Auto.generaMatricola(): numbergeneraMatricola() {
    return this.Auto.prossimaMatricola: numberprossimaMatricola++;
  }

  Auto.marca: stringmarca: string;
  Auto.modello: stringmodello: string;
  Auto.anno: numberanno: number;
  #matricola = class AutoAuto.Auto.generaMatricola(): numbergeneraMatricola();

  constructor(marca: stringmarca: string, modello: stringmodello: string, anno: numberanno: number) {
    this.Auto.marca: stringmarca = marca: stringmarca;
    this.Auto.modello: stringmodello = modello: stringmodello;
    this.Auto.anno: numberanno = anno: numberanno;
  }
}
const const c: Autoc = new constructor Auto(marca: string, modello: string, anno: number): AutoAuto("Honda", "Accord", 2017);
const c: Autoc.#matricola;
Property '#matricola' is not accessible outside class 'Auto' because it has a private identifier.

A differenza della keyword private di TypeScript, questi sono campi davvero privati, che non possono essere facilmente letti a runtime. È importante ricordare, specialmente se scrivi codice lato client, che esistono comunque modi per accedere ai dati dei campi privati attraverso strumenti come il protocollo delle Chrome DevTools. Usa questa funzionalità come strumento di incapsulamento, non come meccanismo di sicurezza.

TypeScript 5 supporta anche i campi #privati statici:

ts
class class AutoAuto {
  static #prossimaMatricola: number;
  static #generaMatricola() {
    return this.#prossimaMatricola++;
  }

  Auto.marca: stringmarca: string;
  Auto.modello: stringmodello: string;
  Auto.anno: numberanno: number;
  #matricola = class AutoAuto.#generaMatricola();

  constructor(marca: stringmarca: string, modello: stringmodello: string, anno: numberanno: number) {
    this.Auto.marca: stringmarca = marca: stringmarca;
    this.Auto.modello: stringmodello = modello: stringmodello;
    this.Auto.anno: numberanno = anno: numberanno;
  }
}

Questo esempio ora ha decisamente più senso — il contatore a livello di classe non è più osservabile in alcun modo dall'esterno della classe, né a compile time né a runtime.

Controllo della presenza di campi privati

Anche se il dato contenuto in un campo privato è privato in un runtime JS implementato correttamente, possiamo comunque rilevare se un campo privato esiste, senza tentare di leggerlo:

ts
class class AutoAuto {
  static #prossimaMatricola: number;
  static #generaMatricola() {
    return this.#prossimaMatricola++;
  }

  Auto.marca: stringmarca: string;
  Auto.modello: stringmodello: string;
  Auto.anno: numberanno: number;
  #matricola = class AutoAuto.#generaMatricola();

  constructor(marca: stringmarca: string, modello: stringmodello: string, anno: numberanno: number) {
    this.Auto.marca: stringmarca = marca: stringmarca;
    this.Auto.modello: stringmodello = modello: stringmodello;
    this.Auto.anno: numberanno = anno: numberanno;
  }
  Auto.equals(altro: unknown): booleanequals(altro: unknownaltro: unknown) {
    if (altro: unknownaltro && typeof altro: {}altro === "object" && #matricola in altro: objectaltro) {
      
altro: Auto
altro
;
return altro: Autoaltro.#matricola === this.#matricola; } return false; } } const const c1: Autoc1 = new constructor Auto(marca: string, modello: string, anno: number): AutoAuto("Toyota", "Hilux", 1987); const const c2: Autoc2 = const c1: Autoc1; const c2: Autoc2.Auto.equals(altro: unknown): booleanequals(const c1: Autoc1); // true

Parte di capire cosa sta succedendo qui è ricordare le regole sui campi e metodi #privati di JS. Potrebbe essere vero che un'altra classe abbia un campo privato #matricola, ma le istanze di Auto non sarebbero in grado di leggerlo. Quindi, se #matricola in altro restituisce true, altro deve essere un'istanza di Auto. Questo è il motivo per cui vediamo il tipo di altro cambiare da unknown ad Auto dopo che questo controllo viene effettuato.

readonly

Anche se non è tecnicamente una keyword di visibilità (perché non ha nulla a che fare con chi può vedere cosa), TypeScript fornisce una keyword readonly utilizzabile con i campi di classe.

ts
class class AutoAuto {
  static #prossimaMatricola: number;
  static #generaMatricola() {
    return this.#prossimaMatricola++;
  }

  public Auto.marca: stringmarca: string;
  public Auto.modello: stringmodello: string;
  public Auto.anno: numberanno: number;
  readonly #matricola = class AutoAuto.#generaMatricola();

  constructor(marca: stringmarca: string, modello: stringmodello: string, anno: numberanno: number) {
    this.Auto.marca: stringmarca = marca: stringmarca;
    this.Auto.modello: stringmodello = modello: stringmodello;
    this.Auto.anno: numberanno = anno: numberanno;
  }

  Auto.cambiaMatricola(num: number): voidcambiaMatricola(num: numbernum: number) {
    this.#matricola = num: numbernum;
Cannot assign to '#matricola' because it is a read-only property.
} }

Param properties

Ok, torniamo un attimo indietro. Ora che conosciamo le keyword di visibilità, torniamo a uno snippet visto in precedenza:

ts
class Auto {
  marca: string;
  modello: string;
  anno: number;
  constructor(marca: string, modello: string, anno: number) {
    this.marca = marca;
    this.modello = modello;
    this.anno = anno;
  }
}

TypeScript fornisce una sintassi più concisa per codice come questo, attraverso l'uso delle param properties (proprietà-parametro):

ts
class class AutoAuto {
  constructor(
    public Auto.marca: stringmarca: string,
    public Auto.modello: stringmodello: string,
    public Auto.anno: numberanno: number,
  ) {}
}

const const miaAuto: AutomiaAuto = new constructor Auto(marca: string, modello: string, anno: number): AutoAuto("Honda", "Accord", 2017);
const miaAuto: Auto
miaAuto
.Auto.marca: stringmarca;

Questa è l'unica occasione in cui vedrai una keyword di visibilità accanto a qualcosa di diverso da un membro di classe. Ecco cosa significa questa sintassi, concettualmente:

ts
class Auto {
  constructor(public marca: string) {}
}

Il primo argomento passato al costruttore dovrebbe essere una string, e dovrebbe essere disponibile all'interno dello scope del costruttore come marca. Questo crea anche un campo di classe public su Auto chiamato marca, assegnandogli il valore che è stato passato al costruttore.

È importante capire in che ordine viene eseguita la "roba del costruttore". Ecco un esempio che ci aiuta a capire come funziona:

ts
class class BaseBase {}

class class AutoAuto extends class BaseBase {
  Auto.proprietaExtra: voidproprietaExtra = var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("inizializzatore del campo di classe");
constructor(public Auto.marca: stringmarca: string) { super(); var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("logica custom del costruttore");
} } const const c: Autoc = new constructor Auto(marca: string): AutoAuto("honda"); // stampa, in ordine: // "inizializzatore del campo di classe" // "logica custom del costruttore"

Nota il seguente ordine di esecuzione all'interno del costruttore della classe:

  1. super()
  2. Inizializzazione delle param properties
  3. Inizializzazione degli altri campi di classe
  4. Qualsiasi altra cosa fosse nel tuo costruttore dopo super()

Nota anche che, mentre in JS è possibile eseguire codice prima di super(), non è possibile accedere a this prima di quel punto — e questo vale anche per i campi che sfruttano le param properties, dato che dietro le quinte vengono comunque assegnati a this:

ts
class class BaseBase {
  constructor() {
    var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("costruttore base");
} } class class AutoAuto extends class BaseBase { Auto.proprietaExtra: numberproprietaExtra = 1; constructor(public Auto.marca: stringmarca: string) { var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(this); // troppo presto: this non esiste ancora
'super' must be called before accessing 'this' in the constructor of a derived class.
super(); var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("logica custom del costruttore");
} }

Override

Un errore comune, che storicamente è stato difficile per TypeScript aiutare a evitare, sono i refusi quando si sovrascrive un metodo di una classe:

ts
class class AutoAuto {
  Auto.clacson(): voidclacson() {
    var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("beep");
} } class class CamionCamion extends class AutoAuto { Camion.clacsonn(): voidclacsonn() { // OPS! refuso nel nome var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("BEEP");
} } const const t: Camiont = new constructor Camion(): CamionCamion(); const t: Camiont.Auto.clacson(): voidclacson(); // "beep" — non quello che volevamo!

In questo caso, sembra che l'intenzione fosse sovrascrivere il metodo della classe base, ma a causa del refuso abbiamo invece definito un metodo completamente nuovo, con un nome diverso. TypeScript 5 include una keyword override che rende più facile individuare questo tipo di errore:

ts
class class AutoAuto {
  Auto.clacson(): voidclacson() {
    var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("beep");
} } class class CamionCamion extends class AutoAuto { override clacsonn() { // OPS!
This member cannot have an 'override' modifier because it is not declared in the base class 'Auto'. Did you mean 'clacson'?
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("BEEP");
} } const const t: Camiont = new constructor Camion(): CamionCamion(); const t: Camiont.Auto.clacson(): voidclacson(); // "beep"

Il messaggio di errore ha persino indovinato correttamente cosa intendevamo fare! C'è un'opzione del compilatore chiamata noImplicitOverride che puoi abilitare per assicurarti che un metodo override correttamente definito rimanga effettivamente un override:

ts
class class AutoAuto {
  Auto.clacson(): voidclacson() {
    var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("beep");
} } class class CamionCamion extends class AutoAuto { clacson() {
This member must have an 'override' modifier because it overrides a member in the base class 'Auto'.
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("BEEP");
} } const const t: Camiont = new constructor Camion(): CamionCamion(); const t: Camiont.Camion.clacson(): voidclacson(); // "BEEP"

Guarda come, una volta che l'override è al suo posto, una modifica alla sottoclasse attira la nostra attenzione:

ts
class class AutoAuto {
  Auto.logClacson(): voidlogClacson() {
    var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("beep");
} } class class CamionCamion extends class AutoAuto { override clacson() {
This member cannot have an 'override' modifier because it is not declared in the base class 'Auto'.
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v22.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("BEEP");
} } const const t: Camiont = new constructor Camion(): CamionCamion(); const t: Camiont.Camion.clacson(): voidclacson(); // "BEEP"

È comune perdere di vista questo tipo di dettagli durante un refactoring, perché ovviamente è del tutto legittimo creare metodi che non sovrascrivono nulla su una sottoclasse. La keyword override, unita a noImplicitOverride, ti dà una rete di sicurezza in entrambe le direzioni.