Recently, I started learning about typescript
and was introduced to the concept of type inference
.
According to my instructor, it's generally not recommended to assign a variable with a specific type
, but to instead rely on type inference
. However, I immediately encountered an issue when I made this mistake:
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);
In the code snippet above, you can see that the string
value was able to slip through type checking, highlighting a potential flaw in relying solely on type inference
. Therefore, would it be better practice to explicitly set the type instead, as demonstrated below?
let number1: number;
number1 = '5';
Upon attempting the above code, an error is immediately thrown. This serves as evidence questioning the reliability of type inference
.