Skip to main content
Module 1 · Lesson 1 of 21/22 in the course~14 min
Module lessons (1/2)

Primitive types and annotations

Warm-Up Stage

The static contract on top of JavaScript

Learn how the TypeScript compiler catches type errors before you even execute a line of code.

JavaScript only checks types while the program is running: a typo on a number passed in place of a string often explodes in production. TypeScript adds a layer of compile-time static analysis: types drive the IDE and block bugs before execution, then disappear completely in the JavaScript output.

Fundamental primitives and inference

The three basic building blocks of any TypeScript program are string, number (includes integers and decimals), and boolean. When you initialize a variable now, TypeScript infers its type automatically; on const, it even infers the exact literal type.

Example 1 — Explicit annotation vs inference on variables

TS
// Annotazione esplicita: utile quando il contratto è documentato subito
const serviceName: string = 'BillingAPI';
const maxRetries: number = 3;
let isHealthy: boolean = true;

// Inferenza idiomatica: TypeScript deduce automaticamente number
let activeConnections = 12;
activeConnections = 15; // OK
// activeConnections = "15"; // TS2322: Type 'string' is not assignable to type 'number'

Example 2 — Function parameters and return values

In strict mode, TypeScript cannot guess the type of a function parameter just by reading the signature: without annotation it fires TS7006 (Parameter implicitly has an 'any' type). Writing down the parameters and return value turns the function into a testable contract.

TS
function calculateTax(amount: number, rate: number): number {
  return amount * (1 + rate);
}

const netTotal: number = calculateTax(100, 0.22);
// calculateTax("100", 0.22); // TS2345: Argument of type 'string' is not assignable to 'number'

The risks of any vs the safety of unknown

Declaring a variable or parameter as any turns off any type checking on that value (and everything that touches it). When the type is not yet known (for example from external input), always use unknown, which forces the type to be verified before use.

Example 3 — Silent contagion of any vs protection of unknown

TS
function parseDangerous(raw: any): number {
  return raw.toFixed(2); // Compila senza avvisi, ma crasha se raw è null!
}

function parseSafe(raw: unknown): string {
  if (typeof raw === 'number') {
    return raw.toFixed(2); // Ristretto a number in sicurezza
  }
  return 'Invalid input';
}

Example 4 — Typed template literals and checks on primitives

TS
function formatBadge(label: string, count: number, urgent: boolean): string {
  const prefix = urgent ? '[URGENT]' : '[INFO]';
  return `${prefix} ${label}: ${count}`;
}

const summary: string = formatBadge('Alerts', 4, false);

Guided practice

Exercise#ts.m1.l1.e1
Attempts: 0Loading…

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

Loading editor…
Show hint

Use the syntax const variableName: type = value; with string, number and boolean.

Solution available after 3 attempts

Exercise#ts.m1.l1.e2
Attempts: 0Loading…

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

Loading editor…
Show hint

Write function greet(name: string): string { ... } and concatenate 'Hello, ' + name.

Solution available after 3 attempts

Exercise#ts.m1.l1.e3
Attempts: 0Loading…

Declares a function called celsiusToFahrenheit that takes a celsius parameter 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.

Loading editor…
Show hint

Apply the formula (celsius * 9) / 5 + 32 with explicit return.

Solution available after 3 attempts

Exercise#ts.m1.l1.e4
Attempts: 0Loading…

Create a function called calculateDiscount that takes a number-type price parameter and a number-type discountPercent parameter, and returns the final discounted price as a number. Explicitly specify both the parameter types and the return type.

Loading editor…
Show hint

Calculate the discount factor as (1 - discountPercent / 100) and multiply it by price.

Solution available after 3 attempts

Check for understanding

TypeScript Quiz#ts.m1.l1.e5
Ready

What happens in strict: true mode when compiling this code?

TS
function addTax(price, tax = 0.22) {
  return price * (1 + tax);
}
Answer options
TypeScript Quiz#ts.m1.l1.e6
Ready

What is the key difference between unknown and any in TypeScript?

Answer options