Variables and Type Annotations

Let's look at Typescript variable types and annotations in this lesson.

More on TypeScript

TypeScript allows but does not require us to annotate our JavaScript code with information about the types of various pieces of data in the code. TypeScript uses this information as a constraint on the values that those pieces of data can contain. If we declare a variable to be a 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 let or const (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:

Get hands-on with 1000+ tech skills courses.