typescript · level 2 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An gives a shape a name, so you write it once.
Writing { name: string; age: number } on every pet gets tiring, and one typo makes two different shapes. An interface names the shape once. Write interface, a name starting with a capital, then curly brackets holding each property and its type, each ending in a semicolon.
Now Pet works as a type label anywhere, like const rex: Pet. Every object labelled Pet must have every property. Leave one out and the checker says TS2741, naming the property that is missing.
interface Pet {
name: string;
age: number;
species: string;
}
const rex: Pet = { name: "Rex", age: 3, species: "dog" };
const tom: Pet = { name: "Tom", age: 7, species: "cat" };
console.log(rex.name, "and", tom.name);
console.log(rex.age + tom.age); An interface is only for the checker. It never shows up in your output.
guess first
One property is missing. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Book {
title: string;
pages: number;
}
const book: Book = { title: "Matilda" };
console.log(book.title);
your turn
Your turn. Design a player for your game.
Fill in the type of each property in the interface. Then give your player a name, a level and true or false for online.
fix it
The checker will not let Biscuit in. Fix it!
- Read the error:
TS2741: Property 'age' is missing. Which object is it talking about? - The
Petinterface promises three properties, but the object on line 6 only has two. - Add
age: 2to the object on line 6, with a comma to separate it, then press run.
nailed it
you gave your shapes a name. :D
- An interface names a shape once, so you can reuse it.
- Every object with that label needs every property.
TS2741means a property is missing from an object.
new words in your collection
- interface
This lesson isn’t saved. A free account remembers every lesson you finish.