Variables and Type Annotations
Let's look at Typescript variable types and annotations in this lesson.
We'll cover the following
That last section was a little on the abstract side, let’s talk more concretely.
TypeScript allows you but does not require you, to annotate your 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 you declare a variable to be a number
, and then assign it the value "3"
, the TypeScript compiler will complain and will not allow the code to be compiled.
If you don’t add any explicit type information, however, you don’t get the full benefit of using TypeScript. It will still catch some errors, such as assigning two different types of values to the same variable or if you try to send a function the wrong number of arguments. By adding as much type information as you can to your code, you will increase the value of TypeScript’s type checking.
Adding type information to TypeScript
You can add type information to TypeScript in a few different ways.
When you assign a value to a variable in TypeScript using let
or const
(using var
is not recommended), TypeScript assumes that you intend that variable to be of the literal type of the assigned value.
If I have code that does this:
let index = 1
TypeScript infers that index
is of type number
. If you try to assign a different value to index
, it will need to be a number. If you pass 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 1200+ tech skills courses.