Search code examples
typescripttype-inference

Typescript - Incorrectly inferring 'never'


This is a basic use-case: Initializing a variable with null then changing the value in some nested loop/function:

let a: number | null = null;
[1].forEach(() => {
  a = 1;
});

if (a != null)
  a.toFixed(); // Error: Property 'toFixed' does not exist on type 'never'.

However typescript infers a's type to be never. I would assume that without the if it would assume it to be null | number in which case I could get an error stating the property does not exist on null, but why is it assuming it to be never based on just the initial assignment value.

Am I doing something wrong?


Solution

  • If you are absolutely sure that a has a value there, than you can put the ! after the variable

    let a: number | null = null;
    [1].forEach(() => {
      a = 1;
    });
    
    if (a !== null)
      a!.toFixed(); //
    

    I would not use null thought but undefined, so no need to use !

    let a: number | undefined;
    [1].forEach(() => {
      a = 1;
    });
    
    if (a) { // <-- if undefined or 0
      a.toFixed(); // No problem here
    }
    

    Also as recommendation use !== not !=