microsoft / microsoft/TypeScript

Possible to narrow type of object literal property with strictNullChecks?

Aperta
#20,219 12 commenti 0 reazioni 1 assegnatario Vedi su GitHub

@sandersn ci sta già lavorando.

Dal 30/1/2018.

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

Descrizione

TypeScript Version: Current playground (2.6?)

Code

type Foo = {
  bar?: number[];
}

let f1: Foo = {};
f1.bar = [];
f1.bar.push(0);

let f2: Foo = { bar: [] };
f2.bar.push(0);

Expected behavior:

Both references to .bar compile successfully.

Actual behavior:

Second reference (f2.bar.push(0)) fails with "object is possibly undefined" -- the type of f2.bar is still treated as number[] | undefined even though it obviously can't be undefined.


This might not be an actual bug as such but whatever magic allows the compiler to narrow the type of f1.bar after assigning to it, should also be able to narrow the type when it was assigned in the literal.

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.

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.