Variables and Type Annotations
More on TypeScript
number and then assign it the string value
"3", the TypeScript compiler will not allow the code to be compiled.
If we don’t add any explicit type information, however, we don’t get the full benefit of using TypeScript. It will still catch some errors, such as if we assign two different types of values to the same variable or send a function the wrong number of arguments. By adding as much type information as we can to our code, we will increase the value of TypeScript’s type checking.
Adding type information to TypeScript
We can add type information to TypeScript in a few different ways.
When we assign a value to a variable in TypeScript using
var is not recommended) TypeScript assumes we intend that variable to be of the literal type of the assigned value.
Assigning with var does two things poorly:
First, it does not prevent a variable. from being redefined in a scope.
Second, it does not have block scope.
If we have code that does this:
let index = 1
TypeScript infers that the
index is of type
number. If we try to assign a different value to
index, it will need to be a number. If we pass an
index to a function, it will only allow it if the expected type of the argument is a number. Try it below: