why typescript can not infer type of expression

Viewed 52

Why one one of these snippets gives TSC error and other does not give? Both of them create same result. nameParts is an array of strings.

  if(nameParts[nameParts.length-1]){

    //error: Type 'string | undefined' is not assignable to type 'string'.
    //   Type 'undefined' is not assignable to type 'string'.
    const lastName:string = nameParts[nameParts.length-1];

  }



  const lastWord = nameParts[nameParts.length-1];
  if(lastWord){
    const lastName:string = lastWord;
  }
1 Answers

TypeScript has pragmatic limits on the depth of analysis it does. With the const declaration, it's trivial to see that lastWord won't be undefined, but without it TypeScript would need to remember that it's seen the guard on nameParts[nameParts.length-1] and that there's been no intervening code that might change nameParts[nameParts.length-1] (by assigning to it, using pop, using shift, etc., etc.). To avoid making the compiler too complex and/or too slow, it just doesn't go that far in the analysis — not least because if you want it to, you can use your second approach with the const.

Related