Перейти к основному содержимому
eLearner.app
Модуль 1 · Урок 1 из 21/14 в курсе~10 min
Уроки модуля (1/2)

Примитивные типы и аннотации

TypeScript is a typed superset of JavaScript, meaning it adds static type syntax on top of existing JavaScript. At runtime, all TypeScript code is compiled to pure JavaScript and types disappear entirely during the build process.

Thanks to TypeScript, you can catch errors before the code runs in the browser, making your development process more robust, safe, and scalable.


Primitive Types

TypeScript supports the standard JavaScript primitive types:

  • string: Represents sequences of characters (e.g. 'Alice', "Hello").
  • number: Represents numeric values, both integers and decimals (e.g. 42, 3.14).
  • boolean: Represents truth values (true or false).
  • null and undefined: Represent intentional or unintentional absence of a value.
TS
const username: string = 'Alice';
const score: number = 100;
const isActive: boolean = true;

Variable Annotations and Inference

In TypeScript, we can add a type annotation by using a colon (:) followed by the type.

If you try to assign a value of a different type (for example, assigning a string to age defined as a number), the TypeScript compiler will immediately raise an error before the code even runs.


The Danger of the any Type

The any type is a special escape hatch that tells TypeScript to completely turn off type checking for that variable.

TS
let data: any = 42;
data = 'Hello'; // No error!
data.nonExistentMethod(); // No error at compile time, but it crashes at runtime!

Using any negates all the safety benefits of using TypeScript. It is considered a bad practice and should almost always be avoided in production code.


Function Annotations and the void Type

We can annotate both the parameters and the return value of a function:

TS
function calculateTax(price: number, taxRate: number): number {
  return price * taxRate;
}

If a function does not return any value (for example, it only does a console.log), its return type is void:

TS
function logMessage(message: string): void {
  console.log(message);
}

Try it yourself

Exercise 1: Typed Variables

Упражнение#ts.m1.l1.e1
Попыток: 0Загрузка…

Declare three explicitly typed variables: username as string with value 'Alice', score as number with value 100, and isActive as boolean with value true. Do not use the any type.

Загрузка редактора…
Показать подсказку

Use the syntax : string, : number, and : boolean after the name of each variable.

Решение доступно после 3 попыток

Exercise 2: Greeting Function

Упражнение#ts.m1.l1.e2
Попыток: 0Загрузка…

Create a function named greet that accepts a parameter name of type string and returns a string in the format 'Hello, ' followed by the name. Explicitly specify both the parameter type and the return type.

Загрузка редактора…
Показать подсказку

Declare the function as function greet(name: string): string { ... } and return the message.

Решение доступно после 3 попыток

Exercise 3: Temperature Converter

Упражнение#ts.m1.l1.e3
Попыток: 0Загрузка…

Declare a function named celsiusToFahrenheit that accepts a parameter celsius of type number and returns the equivalent temperature in degrees Fahrenheit (number). The formula is celsius * 9 / 5 + 32. Explicitly specify both the parameter type and the return type.

Загрузка редактора…
Показать подсказку

Multiply celsius by 9, divide by 5, add 32 and return the result with a : number return type on the function.

Решение доступно после 3 попыток

Exercise 4: Discount Calculation

Упражнение#ts.m1.l1.e4
Попыток: 0Загрузка…

Create a function named calculateDiscount that accepts a parameter price of type number and a parameter discountPercent of type number, and returns the final discounted price as a number. Explicitly specify both the parameter types and the return type.

Загрузка редактора…
Показать подсказку

Subtract the discount percentage divided by 100 from 1, then multiply by the price. Make sure to annotate parameters and return value as number.

Решение доступно после 3 попыток