This can happen in less obvious circumstances, such as if you store a string entered by the user in to a variable, and then add a number to the variable.
TypeScript will check that you've used the correct type on most operators. For example a * b
is only allowed to be used with numbers, and if either side is a string it will be marked as an error, as it doesn't make sense to try to multiply strings. However +
is an exception and is allowed to be used with both strings and numbers for string concatenation, as that is a common feature of programming languages (and also used widely in JavaScript).
It's usually preferable to use template literals instead of +
for producing strings, and stick to only using +
for mathematical addition with numbers, to avoid any confusion around what types you're working with.
Converting between strings and numbers
TypeScript sometimes automatically converts values, such as how string + number will automatically convert number in to a string, and then append it to the first string. Sometimes you want to deliberately convert between types though. For example the user may type a number in to a text input field, which will return a string, but you want to use it as a number instead. It's also often regarded as better programming style to explicitly convert values, rather than relying on implicit language features that convert for you.
There are actually lots of ways to explicitly convert values in TypeScript, but we'll focus on just one for now: using Number()
and String()
functions. Using Number(string)
will convert a string to a number.
// Try entering in to the console:
Number("5") // 5 (number)
Number("-6.5") // -6.5 (number)
Number(5) // 5 (still a number)
Number("Hello") // NaN
Notice in the last number we got the special Not A Number (NaN) result again. This is because the string "Hello" does not represent a valid number, so we get a special result to indicate this.
Similarly, String()
can convert a number to a string.
String(5) // "5" (string)
String(-6.5) // "-6.5" (string)
String("Hello") // "Hello" (still a string)
String(NaN) // "NaN" (string)
Note that numbers can always be converted to a string. If you convert the special NaN value to a string, you get a string which says "NaN". (This conversion is successful; it's correctly turned a number value in to a corresponding string.)
Also note that in both cases, if you convert a type to the same type, like String("Hello")
, it just returns the same value unaltered.