Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Typed variable declaration | TypeScript Fundamentals
Introduction to TypeScript
course content

Зміст курсу

Introduction to TypeScript

Introduction to TypeScript

1. TypeScript Fundamentals
2. Conditional Statements
3. Arrays
4. Loops
5. Functions

bookTyped 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:

12
let one : number = 10; console.log(one)
copy

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:

12
let variable : string = 'Hello c<>definity!'; console.log(variable);
copy

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:

12
let variable : boolean = true; console.log(variable);
copy

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.

Translate from English to TypeScript: "Let the name be a string and let it be 'C<>definity'!"

Translate from English to TypeScript: "Let the name be a string and let it be 'C<>definity'!"

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 5
We're sorry to hear that something went wrong. What happened?
some-alt