Most chapters in the book have practical exercises. These exercises are designed to test your understanding of the material.
You can run the exercises by visiting the GitHub repository for the book, at https://totalts.link/e-repo.
There, you'll find instructions for cloning the repository to your local machine, installing the dependencies, and running the exercises.
Each exercise in the book will have a link to our site, Total TypeScript, where you can find an online version of the exercise. There will also be a handy button to open the exercise in your local editor.
Most of the exercises will involve this process:
- Read the instructions.
- Open the code in your local editor.
- Start the exercise CLI, which checks your work as you go.
- Fix the TypeScript errors and runtime errors until the exercise is complete.
- Check your work against my solution.
Let's quickly discuss a couple of conventions and tools used in the exercises:
TypeScript checks your code in your editor for things it thinks might fail when the code is run. It shows these issues as red squiggles under the code.
For instance, calling a method on null:
const x = null;
x.toUpperCase(); // Error: Property 'toUpperCase' does not exist on type 'null'.TypeScript also provides a directive to tell TypeScript to expect an error on the following line:
const x = null;
// @ts-expect-error
x.toUpperCase();Now, the error no longer appears - because TS is expecting it.
This is very useful as a teaching tool, since it allows me to write exercises which expect errors. So if you see a @ts-expect-error comment, we are expecting a TypeScript error on the following line.
TypeScript only checks your code in your editor. To make the exercises as realistic as possible, I've also added a few runtime tests.
These tests are written with Vitest, a popular testing framework for TypeScript.
We're not using many complex Vitest features, only a few simple ones.
For instance, this test checks if 1 + 1 equals 2:
import { expect, it } from "vitest";
it("1 + 1 = 2", () => {
expect(1 + 1).toBe(2);
});it is the function used to define a test. expect is a function used to make assertions.
The tests will be automatically run by the exercise CLI as you work through the exercises.