Contenido del Curso
Introduction to TypeScript
Introduction to TypeScript
Typed variable declaration
Since TypeScript is a superset of JavaScript, there aren't many differences in basic syntax. But now, let's take a look at one of the most important differences - typing.
TypeScript introduces the concept of typed variables, where the type of each variable is explicitly defined. Among the various data types supported by TypeScript, three commonly used types are number
, boolean
, and string
.
Previously, we declared variables using the var
keyword, and TypeScript automatically inferred the type of that variable. Now, we will make TypeScript's job easier and manually define the variable's type. This is done as follows:
let one : number = 10; console.log(one)
The syntax is slightly different, and we see what type our variable one
will be. Let's take a closer look at the syntax:
In the same way, we can define variables of the other two types, for example, a string:
let variable : string = 'Hello c<>definity!'; console.log(variable);
You may have noticed that it's as if we are commanding our code: Let the variable be a string!
This way, it will be easier for you to remember the syntax.
boolean
Now let's move on to the boolean
type, which is a data type that can only hold the values true
and false
.
Q: What's it used for?
A: It's used for executing code blocks with conditions.
Q: What are code blocks with conditions?
A: You'll learn about them later in this course.
Let's take a look at a variable with the boolean type:
let variable : boolean = true; console.log(variable);
What is data typing used for?
Primarily, data typing helps a programmer better understand their code. You have the freedom to decide whether to use data typing or not, but TypeScript is highly regarded for this feature.
Additionally, data typing helps avoid errors, as the TypeScript compiler will highlight code fragments where data types don't match, as shown in the screenshot:
We defined variables with the types number
and string
. Then we try to divide a numeric value by a string. The compiler warns us that we might be making a mistake. The compiler takes good care of us.
¡Gracias por tus comentarios!