Static vs dynamic typing
let's replace the content of the onStartup
- First, let's replace the content of the
onStartup
function: - Let's now surround number 5 with quotes:
'5'
- Let's try another test, copy the following condition into your code, but before you paste it think for a moment and try to guess what will be the output:
You will see that TypeScript complains about the second assignment of test:
This code would work perfectly fine in JavaScript which allows dynamic change of types. You might think, that
this approach is better, however, although it might look easier for a developer it is not.
Imagine that there you are working on a project with a team of developers and one of them by mistake changes
the type of your variable from number
to string
. All logic based on that variable
will be broken now (as it would be comparing a variable to a number).
This time the compiler won't complain because we have cast our 5 from a number to a string. As a result we
can assign it to our variable, however, we have to remember that it will be treated as a string
and not a number
.
Once you paste the following condition into your code, TypeScript generates an error:
Once again, this condition would execute in plain JavaScript and could lead us to an error. By looking at the
code you might think that result of the comparison will be true, but due to different types, it would
evaluate to false
. TypeScript protects you from making such mistakes warning that you are
trying to compare different types.