typescript · level 2 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a nickname for any type you like.
Write type, a name, = and a type: type Pounds = number;. Now Pounds means number everywhere, but your code also says what the number is for.
An alias can name an object shape too: type Point = { x: number; y: number };. For objects, an alias and an interface do nearly the same job. Many teams use interfaces for objects and aliases for everything else. Pick one style and stick with it.
Both are strict about extras. Put a property in a new object that the shape does not list and the checker says TS2353. That catches typos in property names.
type Pounds = number;
type Point = { x: number; y: number };
const ticket: Pounds = 4.5;
const home: Point = { x: 2, y: 5 };
console.log(`A ticket costs £${ticket}.`);
console.log(`Home is at ${home.x}, ${home.y}.`); An alias never makes a new kind of value. Pounds is still a plain number.
guess first
An alias inside an alias. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Name = string;
type Team = { captain: Name; size: number };
const reds: Team = { captain: "Ana", size: 11 };
const blues: Team = { captain: "Jo", size: reds.size - 4 };
console.log(blues.captain, blues.size);
your turn
Your turn. Label a journey.
Fill in the type that Minutes stands for, then plan a journey: where from, where to, and how many minutes it takes.
fix it
A typo slipped into the order. Fix it!
- Read the error:
TS2561. The checker does not know one of the property names in the object on line 2. - Compare the spelling on line 2 with the alias on line 1, letter by letter.
- Change
quantatytoquantityon line 2, then press run.
nailed it
you can name any type you like. :D
typegives any type a new name, called a type alias.- Aliases and interfaces can both describe object shapes.
- The checker refuses properties a shape does not list.
new words in your collection
- type alias
This lesson isn’t saved. A free account remembers every lesson you finish.