Show contents
Chapter 1 of 7 · 20 min
Basic types
By the end of this chapter, you'll be able to
- Explain what TypeScript checks and when
- Annotate variables, arrays and functions
- Let TypeScript infer types whenever possible
- Use unions and literal types to limit the possible values
JavaScript, with types on top
TypeScript is a superset of JavaScript: almost any valid JavaScript code is valid TypeScript. You add type annotations, and the tsc compiler does two things:
- it checks that the types are consistent, without running the code;
- it outputs plain JavaScript, removing the annotations. That JavaScript is what runs, in the browser or with Node.js.
This JavaScript is what runs. Types no longer exist at run time.
Text description of the animation
- You write JavaScript, with types on top.
- The compiler checks that each value matches its type. If there is an error, it warns you before anything runs.
- It outputs JavaScript: the types are gone, they were only used for checking.
- This JavaScript is what runs. Types no longer exist at run time.
In a project, you install TypeScript with npm, then npx tsc compiles the files according to the tsconfig.json configuration. The labs of this course do all of this in your browser, with TypeScript 5.9 in strict mode, the recommended setting.
Annotate variables
The type goes after the name, preceded by a colon:
const city: string = "Abidjan";
let population: number = 6_300_000;
const isCapital: boolean = false;
console.log(`${city}: about ${population} inhabitants`);
Abidjan: about 6300000 inhabitants
_ separates thousands for readability, without changing the value. The basic types are JavaScript's: string, number (integers and decimals), boolean, null and undefined.
Most of the time, you do not need to write the type: TypeScript deduces it (this is called inference) from the initial value. It then keeps that type:
let price = 1500;
price = "free";
TS2322: Type 'string' is not assignable to type 'number'.
price was inferred as number: assigning a string to it is refused. Each error has a code (TS2322) you can look up in the documentation.
Arrays and functions
An array is typed with [] after the type of its elements. For a function, you annotate the parameters and, if you wish, the return value:
const marks: number[] = [14, 9, 17];
function average(values: number[]): number {
let sum = 0;
for (const v of values) sum += v;
return sum / values.length;
}
function round(n: number, decimals = 1): number {
const f = 10 ** decimals;
return Math.round(n * f) / f;
}
console.log(round(average(marks)));
console.log(round(Math.PI, 3));
13.3
3.142
decimals = 1 is a parameter with a default value: its number type is inferred. Other parameters must be annotated: in strict mode, a parameter without a type is an error (TS7006). Thanks to the annotations, a wrong call is reported straight away:
function average(values: number[]): number {
return values.reduce((a, b) => a + b, 0) / values.length;
}
const inputs = ["14", "9"];
average(inputs);
TS2345: Argument of type 'string[]' is not assignable to parameter of type 'number[]'.
Unions and literal types
A union A | B accepts a value of either type. A literal type accepts only one precise value. Together, they describe exactly the allowed values:
type Currency = "XOF" | "EUR" | "USD";
function format(amount: number, currency: Currency): string {
return `${amount.toFixed(2)} ${currency}`;
}
console.log(format(2500, "XOF"));
console.log(format(12.5, "EUR"));
2500.00 XOF
12.50 EUR
type Currency = … creates an alias: a name for a type. Writing format(10, "GBP") would be refused, because "GBP" is not part of the union. Your editor even suggests the three possible values when you type the quote.
Mini-lab: the price including taxTypeScript
Output
Click “Run”: the TypeScript compiler will be loaded in your browser (about 3 MB the first time). Your code is checked, then run if it has no type error.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: temperature conversion
Write a function convert(value, to) where to can only be "C" or "F". To "F", it computes value × 9 / 5 + 32; to "C", (value − 32) × 5 / 9. It returns a string such as "86 °F", rounded to the nearest integer. Display the conversion of 30 °C to °F and of 50 °F to °C.
Hint 1
type Unit = "C" | "F";.Hint 2
to === "F" ? … : … picks the formula.Show the solution and common mistakes
type Unit = "C" | "F";
function convert(value: number, to: Unit): string {
const result = to === "F" ? value * 9 / 5 + 32 : (value - 32) * 5 / 9;
return `${Math.round(result)} °${to}`;
}
console.log(convert(30, "F"));
console.log(convert(50, "C"));
86 °F
10 °C
Common mistakes:
- Annotating
to: string: the code works, butconvert(30, "K")would be accepted and give a wrong result. The union limits the values as you write. - Forgetting the parentheses in
(value - 32) * 5 / 9: multiplication comes before subtraction. TypeScript checks types, not your formulas.
Summary
- 1TypeScript checks types before running, then outputs JavaScript without annotations.
- 2You annotate with a colon: const city: string, function f(x: number): number.
- 3Inference deduces the type from the initial value: only annotate what helps, such as parameters.
- 4Unions and literal types ("XOF" | "EUR") limit the allowed values.
- 5any switches checking off: avoid it.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.