In JavaScript, a variable happily holds a number one moment and a string the next — and you only find out something went wrong when the program is already running. TypeScript fixes this with type annotations: a small label after the variable's name that tells the compiler what kind of value lives there, forever.
The annotation goes after a colon, between the name and the =:
let score: number = 90; // score holds numbers, always
const player: string = "Alice"; // player holds a string, and const means it never changes
From this line on, score is a number. You can do number things with it (score = score + 8;) and the compiler is happy. It works with both let and const.
Typed functions:
Annotations shine on functions. You label each parameter AND the value the function returns — the return type goes after the parameter list:
function add(a: number, b: number): number {
return a + b;
}
Now nobody can call add("2", 3) by accident, and everyone knows add gives back a number. Try it and the compiler answers with error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
The trap:
An annotation is a promise, and the compiler holds you to it. This looks innocent:
let count: number = 5;
count = "42"; // "42" is a string, not a number!
...but the compiler reports an error on the second line:
error TS2322: Type 'string' is not assignable to type 'number'.
Read that message carefully — you WILL see it again. It names the type you gave ('string') and the type you promised ('number'). That's not the compiler being mean: it just caught, before the program ever ran, a bug JavaScript would have let slip through.
Assignment
Follow the Coding Tutorial and put annotations to work:
- declare
let score: number = 90;and add8to it, - declare
const player: string = "Alice";, - define
function add(a: number, b: number): numberreturninga + b, - print
player + " scored " + score, then print"add(2, 3) = " + add(2, 3).
The exact expected output is:
Alice scored 98
add(2, 3) = 5
Hint
The annotation always follows the name: name: type. For functions, the return type comes after the closing parenthesis: (a: number, b: number): number.
Free plan: 30 tutor messages. PRO is unlimited.
