Isaac
Isaac

Reputation: 12874

How reliable is type inference?

I am just starting to pick up typescript and came across type inference.

Now according to the instructor, it's not best practice to initialize variable with type but to rely on type inference but immediately I made this error as below

function add(n1: number, n2: number, showResult: boolean, phrase: string) {
  const result = n1 + n2;
  if (showResult) {
    console.log(phrase + result);
  }
  return result;
}

let number1;
number1 = '5';
const number2 = 2.8;

add(number1, number2, printResult, resultPhrase);

From the code snippet above, it clearly let string slipped thru type checking and so instead, will it be a better idea if we don't rely on type inference but to explicitly set the type instead? Such as below

let number1: number;
number1 = '5';

and immediately we get error from above code. Below image is the proof to not trust type inference.

enter image description here

Upvotes: 1

Views: 224

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

number1 is typed as any, because nothing is assigned to it when it's declared. And any is, unfortunately, assignable to anything - this is why using it is strongly discouraged. With

function add(n1: number,

if you call add where the first argument passed is of type any, it'll compile.

Assigning another value to the variable after the variable has been declared doesn't change the type - Typescript still sees it typed as any.

To keep from making these sorts of mistakes, make sure to enable noImplicitAny in your tsconfig - it will throw errors when you attempt to use an any where a more specific type is expected.

Something else that helps is to use const instead of let - with const, the type will always be inferred automatically. You may occasionally need to annotate a more specific type than the inferred one, but at least the inferred type will always be something specific, and not any. (const should be preferred over let whenever possible anywy)

If you do have to use let - which is occasionally necessary - then either assign it a value on initialization (and type inference will work), or use a type annotation like

let number1: number;

so that it's typed properly, otherwise it'll be any and will cause problems.

Using a type annotation when a variable initially doesn't have anything assigned to it is perfectly fine.

Upvotes: 3

Related Questions