microsoft / microsoft/TypeScript

Nullish coalescing should always include the type of the right operand

Aperta
#36,393 8 commenti 6 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

In Discussion Suggestion
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
2g 4h
PR unite (30g)
132

Descrizione

$ ./node_modules/.bin/tsc --version
Version 3.7.2

Search Terms:

Code

A toy example would be something like this.

let foo: string = "";
foo = "bar" ?? 123;

This one is obviously fine since "bar" is always truthy.

However, this becomes a little bit problematic when you consider the idiom of having Record objects and checking their truthiness before using them.

const elts = ["foo", "bar", "spam", "spam", "foo", "eggs"];
const counts: Record<string, number>;
for (const elt of elts) {
  // This really **should** raise an error.
  counts[elt] = counts[elt] ?? "zero";
  counts[elt] += 1;
}

Expected behavior:
An error should be raised.

Actual behavior:
Curiously, an error is not raised in strict mode but is raised in un-strict mode.

$ ./node_modules/.bin/tsc ./foo.ts 
foo.ts:5:3 - error TS2322: Type 'number | "zero"' is not assignable to type 'number'.
  Type '"zero"' is not assignable to type 'number'.

5   counts[elt] = counts[elt] ?? "zero";
    ~~~~~~~~~~~


Found 1 error.
$ ./node_modules/.bin/tsc --strict ./foo.ts
# No error, exits 0 and emits JS.

Playground Link:
Playground Link

Toggling the strictNullChecks config option will show the issue.

Related Issues:

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Riproduci gli esempi con TypeScript 3.7.2 usando sia il comando predefinito del compilatore sia --strict, quindi confronta le diagnosi per l’assegnazione con coalescenza dei null. Il lavoro è completato quando l’espressione segnalata include in modo coerente il tipo dell’operando destro e genera l’errore previsto con la configurazione indicata.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.