×

typescript · level 2 · unit 1 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.