bdwain
bdwain

Reputation: 1745

Typescript not inferring correct type when it changes in a called function

When I initialize a variable to null, but with another type as a union (e.g. number | null), it seems to lose the non-null type information immediately (the same thing happens with undefined, except if I leave it unitialized, rather than explicitly setting it to undefined).

let foo: number | null = null;

foo; //foo's type (seen by mousing over) is "null", not "number | null"

function blah() {
  foo = 123; //foo is "number | null"
}
blah();

foo; //foo's type is "null", not "number | null"

TS Playground

Is there a way to access the type of foo correctly there?

Upvotes: 0

Views: 82

Answers (1)

bdwain
bdwain

Reputation: 1745

Turns out this is a known trade off https://github.com/microsoft/TypeScript/issues/9998

Upvotes: 1

Related Questions