Line At A Time
Lesson 5: Custom Types
Custom Types Invent your own type with its own shape.
1type Player = {
2 name: string;
3 score: number;
4};
5
6const ada: Player = { name: "Ada", score: 100 };
7console.log(`${ada.name} scored ${ada.score}`);
Terminal
$ npx tsc main.ts
$ node main.js
Ada scored 100
Every line, explained
type Player = {
type lets you invent YOUR OWN type and give it a name. Player is now a real type you can use, just like string or number. The curly braces describe its shape. By convention, custom type names start with a capital letter.
name: string;
Every Player must have a name, and it must be a string.
score: number;
...and a score, which must be a number.
};
This }; finishes describing the Player type. Nothing has "run" yet; a type is a description, not a value.
const ada: Player = { name: "Ada", score: 100 };
ada is declared as a Player, so TypeScript checks the object against the shape: forget score, or spell name wrong, and it refuses to compile. This object has exactly the right pieces, so all is well.
console.log(`${ada.name} scored ${ada.score}`);
console.log(...) works exactly as it does in JavaScript; TypeScript IS JavaScript underneath, so everything from Intro to JavaScript still applies. You read the pieces back with a dot: ada.name, ada.score. You've now built your own type: the heart of real-world TypeScript!