Reading type annotations
You'll learn to read type annotations: : string, : number[], and the types on a function's inputs and output.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You open a file AI wrote and see function total(list: number[]): number. It looks like JavaScript with
extra bits. Those extra bits are types, and they tell you exactly how to use the function.
Think of a form at the bank. Each box has a small label under it: "name, in letters", "amount, in numbers". The label doesn't fill the box. It says what is allowed in it. A type annotation is that label.
Read the colon as "is a". city: string means "city is a string".
let city: string = "Dhaka";const isPaid: boolean = false;const prices: number[] = [120, 60, 250];const names: Array<string> = ["Rafi", "Nusrat"];
The basic types are string (text), number (any number, with or without decimals) and boolean
(true or false). Add [] for a list: number[] is "an array of numbers". Array<string> is the
same as string[], written another way. You'll see the < > form in React too: useState<number>(0)
means "this state holds a number". The type inside < > is what goes inside.
Functions get labels on each parameter, and one more after the ) for what comes back:
function total(list: number[]): number {let sum = 0;for (const p of list) sum += p;return sum;}
list: number[] says what goes in. The : number after ) is the return type: what comes out. An
arrow function has the same parts: (n: number): number => n / 2.
Often there is no label at all. In let marks = 85;, TypeScript sees 85 and works out that marks is a
number by itself. This is called type inference. In VS Code, hover over any name to see its type.
People often mix up the two colons. Inside an object, { name: "Rafi" }, the colon gives a value.
After a variable or parameter, name: string, the colon gives a type. If the right side is a real
value ("Rafi", 85), it is an object. If it is a type word (string, number), it is a label.
When you read a typed function, read it like a sentence: "total takes a list of numbers and gives back a number."
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1const marks = [80, 95, 70];
marks?1function greet(name: string, year: number): string {2 return `Hi ${name}, year ${year}`;3}4greet("Rafi", 2);5greet(2, "Rafi");6greet("Nusrat", 3);
Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3In
function total(list: number[]): number, what does the lastnumbermean? - 2 / 3Which type is the same as
string[]? - 3 / 3
let city = "Dhaka";has no type label. What type does TypeScript givecity?
Explain it back
How confident are you with Reading type annotations?
Done
function total(prices: number[]): number and say what goes in and what comes out.