TypeScript: Zero to Hero
Programming from the very first line, in TypeScript: values, decisions, loops, functions and data, with a compiler that reads your code before it runs and tells you what is wrong. No experience needed, and by the end you write typed, idiomatic programs of your own.
- Beginner
- 8 units, 24 lessons, 312 exercises
- TypeScript
- No experience needed
Unit 01 · 3 lessons
First steps
Write small programs that calculate, remember values and print results
- 01Values and expressions
Numbers, text, and the order a calculation happens in
- 02Variables and types
Names for values, and the compiler that checks them
- BOSSA receipt
Prices, a discount and tax turned into a formatted total
Read the unit guide
A program is a list of instructions called statements. The computer runs them from top to bottom, one at a time. console.log(...) is the statement you will use most: it prints whatever is inside its brackets on a new line.
Programs work with values. Numbers are written plainly (5, 3.5) and calculated with +, -, *, /, % (remainder) and ** (power). Multiplying and dividing happen before adding and subtracting, and brackets go first. Text is called a string and sits inside quotes: "2 + 3" is five characters, not a sum. + between two strings joins them.
A variable is a name for a value. let total = 20; creates one, and total = total + 5; stores a new value in it. const creates a variable that can never be given a new value. Use const unless you know the value has to change.
Every value has a type: number, string or boolean (true or false). A variable keeps the type of its first value for good. You may write the type yourself, let age: number = 30;, or leave it out and let it be worked out from the value.
Before a TypeScript program runs, a tool called the compiler reads all of it. If any line breaks the rules, for example a string stored in a number variable, nothing runs at all and you get a message naming the line. A compile error is a favour: you hear about the mistake before anyone uses the program.
The classic pitfall: a program that compiles is not yet a correct program. The compiler checks types, not your arithmetic. A total that is off by a discount, or 0.1 + 0.2 printing 0.30000000000000004, are mistakes only you can catch, by running the program on numbers whose answer you already know.
Unit 02 · 3 lessons
Decisions and loops
Make a program choose between paths and repeat work until it is done
- 01Conditions
Comparisons, if and else, and combining questions
- 02Loops
Repeat a block with while and for, and trace it by hand
- BOSSFizzBuzz and friends
Loops and conditions together, and the off-by-one error
Read the unit guide
A comparison asks a question and answers with a boolean. >, <, >= and <= compare sizes, === asks "equal?" and !== asks "not equal?". Three equals signs compare; one stores. && (and) is true when both sides are true, || (or) when at least one is, and ! flips a boolean.
if (condition) { ... } runs its block only when the condition is true. Add else if for further questions and else for everything left over. The questions are asked from the top and the first true one wins, so their order matters. For a small either-or value there is the ternary: condition ? a : b.
A loop repeats a block. while (condition) { ... } keeps going as long as the condition is true. for (let i = 0; i < 3; i++) { ... } packs a counter into one line: where it starts, the condition to keep going, and the step after each trip. for (const ch of text) hands you each character of a string in turn. break leaves a loop early and continue skips to the next trip.
To understand a loop, be the computer: write down the value of each variable after every trip. A running total (total += i) and a counter (count += 1) are the two patterns you will meet everywhere.
The compiler helps here too. Comparing a number with a string using === can never be true, so it is rejected as a mistake before the program runs.
The classic pitfall is the off-by-one error: a loop that runs one time too few or too many, usually because of < where <= was meant. The other is the loop that never ends, because nothing inside it changes the variable its condition looks at. Check the first trip, the last trip, and what makes it stop.
Unit 03 · 3 lessons
Functions
Name a piece of work once, and say what goes in and what comes out
- 01Defining functions
Parameters, return values, and calls the compiler checks
- 02Arrow functions and scope
Where a variable lives, and functions written as values
- BOSSA text toolkit
A palindrome check, a vowel counter and a Caesar shift
Read the unit guide
A function is a named block of code. function double(n: number): number { return n * 2; } defines one, and double(4) runs it: that is a call. Defining a function runs nothing. Calling it runs its block with the values you pass in.
The names in the brackets are parameters: variables that receive their values from the call. Each parameter needs a type, and the compiler checks every call against it, so double("4") is rejected before the program runs. The type after the brackets is the return type.
return hands a value back to the place of the call and ends the function at once. That is different from printing: console.log shows a value to a person, return gives it to the rest of the program. A function that returns nothing has the return type void.
A variable lives inside the curly brackets where it was created. That region is its scope. Code inside a function can read variables from outside it, but nothing outside can see a function's own variables. A parameter can be optional (mark?: string, possibly undefined) or have a default (hi = "Hi").
An arrow function is a function written as a value: const double = (n: number) => n * 2;. A function can even return another function, and the inner one keeps access to the variables around it. That is a closure.
The classic pitfall is printing where you meant to return. The function looks fine when you run it alone, and then its caller receives undefined. Keep functions small, give each one job, and check each with inputs whose answers you already know, including one where the answer is "no".
Unit 04 · 3 lessons
Collections
Keep many values under one name, and give their shape a type
- 01Arrays and tuples
Ordered lists, numbered from 0, with a type for their items
- 02Objects and their types
Named values, and shapes the compiler checks
- BOSSA gradebook
An array of typed records: averages, the best, groups, a ranking
Read the unit guide
An array holds many values in order: const scores = [70, 85, 90];. Its items are numbered from 0, like the characters of a string, so scores[0] is the first and scores[scores.length - 1] is the last. The type number[] means "an array of numbers", and the compiler keeps everything else out. push adds at the end, pop removes from the end, includes asks whether a value is present, and slice copies a part.
An object groups named values: { name: "Rex", age: 3 }. The names are its properties, read and changed with a dot: pet.age. Give the shape a name with type Pet = { name: string; age: number }; (or interface Pet { ... }) and the compiler checks every object against it: a missing property, a wrong type or a misspelt name is rejected before the program runs. A ? marks a property as optional.
Two shortcuts save typing. Destructuring pulls properties into variables: const { name, age } = pet;. Spread copies them into a new object: { ...pet, age: 4 } is a copy with one property replaced.
Real data is usually an array of objects: a list of students, each with a name and a score. A loop over it gives totals and averages, an if inside the loop finds the best, and sort with a small comparing function puts it in order. A Record<string, number> is an object used as a lookup table, for counting things by name.
A tuple is an array with a fixed length and a type for each position, such as [string, number]. readonly in front of an array type forbids changing it.
The classic pitfall: assigning an array or an object to a second variable does not copy it. Both names refer to the same thing, so a change made through one shows through the other. const does not help: it stops the name being given a different array, not the array being changed. Copy with slice() or spread when you need a separate one.
Unit 05 · 3 lessons
Text and Data
Cut text into pieces, turn the pieces into typed data, and reshape that data with array methods
- 01Strings
Cut, clean and glue text, and turn it into numbers
- 02Array methods
map, filter, reduce and friends: say what you want, not how to loop
- BOSSA log report
Parse lines of text into records, then count, group and rank them
Read the unit guide
Most programs take data in one shape and hand it back in another: a line of text becomes a record, a list of records becomes a total or a ranking. This unit gives you the tools for both halves.
A string never changes in place. Every string method returns a new string (or an array, or a number), and the original stays as it was, so keep the result in a variable. trim removes spaces at both ends, split cuts text into an array, join glues an array into text, slice copies a part, includes answers yes or no, replace swaps the first match and padStart fills up the front.
Text that looks like a number is still text: "12" + 1 is "121". Number(text) converts it, and gives NaN, "not a number", when the text has no number in it. The compiler cannot see that coming, so ask Number.isNaN(n) yourself.
Array methods replace most loops. map turns every item into a new item, filter keeps the items that pass a test, reduce folds the whole array into one value, find gives the first match, some and every answer yes or no. The compiler follows the types through a chain: a number[] mapped to text is a string[].
sort is the odd one out: it changes the array itself, and without a comparator it sorts as text, which puts 10 before 9. Always pass one: (a, b) => a - b for smallest first, b - a for largest first.
The pattern of the boss lesson is worth remembering: parse each line into a typed record once, at the door. After that every question about the data is a short chain of array methods.
Unit 06 · 3 lessons
Unions and Errors
Say exactly which values are possible, handle each one, and keep bad data from crashing the program
- 01Unions and narrowing
A value that is one of several types, and how to find out which
- 02Errors and modules
Catch what goes wrong at run time, and split a program across files
- BOSSAn inventory that saves itself
Load stock from text, check it, change it, save it, and survive bad input
Read the unit guide
A union type lists alternatives: string | number is "a string or a number". The compiler will not let you treat the value as one of them until you have proved which it is. A check such as typeof v === "string" or v === null does that: inside the if the type is narrowed. Literal types narrow the choice further, down to exact values: "left" | "right".
null and undefined both mean "nothing here". Under strict they are not allowed to hide inside a string: the type has to admit it, as in string | undefined, and then you must deal with it. a?.b reads a property only if a is there. a ?? b supplies a fallback.
When a value comes in several shapes, give every shape a kind property with its own literal value. Checking kind tells the compiler which shape you hold, and which properties exist.
Errors at run time are thrown. try and catch stop one from ending the program; throw new Error("...") raises your own. What you catch has the type unknown, because anything can be thrown: check err instanceof Error before reading err.message. A result type, { ok: true, ... } | { ok: false, ... }, puts failure into the return value, where the compiler makes the caller look at it.
The boundary is where types stop helping. JSON.parse returns any, a type that switches the compiler off, so a wrong shape flows in silently. Annotate what comes in as unknown, then ask at run time: is it an object, is it not null, does it have the key, is the value the right kind? After those checks the compiler trusts the data, and so can you.
Programs also grow past one file. Each file is a module: export what others may use, import it by name where it is needed. Everything else stays private to its file.
Unit 07 · 3 lessons
Classes and Generics
Build reusable shapes: classes that guard their own data, and code that works for many types without losing track of them
- 01Classes
A recipe for objects that carry their own data and methods
- 02Generics
Code that works for any type and still knows which one it got
- BOSSA bank
Accounts and transfers, with rules held by types where possible and by code where not
Read the unit guide
A class describes a kind of object: the data each one holds (its properties, called fields in a class) and what it can do (methods). new builds one object and runs the constructor. Inside the class, this is the object the method was called on, so every object works on its own data.
A class can guard that data. private fields are usable only inside the class, readonly fields are set in the constructor and then fixed, and a getter (get total()) offers a value to read without offering a way to change it. Writing private or readonly in front of a constructor parameter declares the field and fills it in one go. implements promises that the class has everything an interface lists, and the class name is itself a type.
Generics are for code that should work with many types and still keep track of which. function first<T>(xs: T[]): T has a type parameter, T. The compiler fills it in at each call, so a list of strings gives back a string, not "something".
Inside a generic function the compiler knows nothing about T. A constraint, T extends HasLength, limits the choice and in exchange lets the body use what the constraint promises. keyof User is the union of the field names of User. The utility types build new types from old ones: Partial<User> makes every field optional, Pick<User, "id"> keeps some, Record<string, number> maps keys to values.
The boss lesson shows the dividing line. Rules about who may touch what, and which values exist at all, belong in types: the compiler enforces them for free. Rules about amounts ("never below zero") depend on values that only exist at run time, so they are code: a method that checks and refuses.
The classic pitfall is thinking private protects the data itself. It protects a name. A getter that returns the private array hands out the real thing, and anyone can push to it. Return it as readonly, or return a copy.
Unit 08 · 3 lessons
Hero
Write code that waits without freezing, and design types so that wrong states cannot even be written down
- 01Asynchronous code
Results that arrive later: promises, async and await
- 02Designing with types
Shape your types so that wrong states cannot be written down
- BOSSA task manager
One program from an empty file: model, commands, storage, tests and a refactor
Read the unit guide
Some work takes time: a timer, a file, a request over the network. The program does not freeze while it waits. It gets a promise, a placeholder for a result that arrives later. Promise<number> will hold a number. await pauses the function it is in until the promise is ready and hands over the value; a function that uses await is marked async, and always returns a promise itself.
Forget an await and you are holding the placeholder, not the value. The compiler catches most of these, because a Promise<number> is not a number. It cannot catch a forgotten await on something whose result you ignore, such as a save: the program simply moves on before the work is done.
Promises start working when they are created. Awaiting two in a row takes the sum of their times; creating both and awaiting Promise.all takes only as long as the slower one, and gives the results in the order you passed them. A promise that fails throws at the await, so try and catch work, as long as the await is inside the try.
Designing with types means making wrong states impossible to write. A bag of optional properties allows combinations that make no sense. A union of shapes, each with its own state or kind, allows only the real ones. as const keeps exact values instead of widening them to string. A final const left: never = value is a tripwire: add a case to the union later and every function that forgot it stops compiling.
A type guard, a function returning v is Cat, packages a run-time check so the compiler can use it. The compiler trusts the guard completely, so the body has to check enough.
The capstone puts it together: a typed model, commands as a union, one function that applies a command and returns a new list, asynchronous storage with a checked boundary, tests, and a compiler that points at everything a change touches. That is how real TypeScript programs are built.
Learn TypeScript: Zero to Hero on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.