Module lessons (1/2)
Primitive types and annotations
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
// 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.
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
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
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
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.
Show hint
Use the syntax const variableName: type = value; with string, number and boolean.
Solution available after 3 attempts
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.
Show hint
Write function greet(name: string): string { ... } and concatenate 'Hello, ' + name.
Solution available after 3 attempts
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.
Show hint
Apply the formula (celsius * 9) / 5 + 32 with explicit return.
Solution available after 3 attempts
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.
Show hint
Calculate the discount factor as (1 - discountPercent / 100) and multiply it by price.
Solution available after 3 attempts
Check for understanding
What happens in strict: true mode when compiling this code?
function addTax(price, tax = 0.22) {
return price * (1 + tax);
}What is the key difference between unknown and any in TypeScript?