Course outline · 0% complete

0/26 lessons0%

Course overview →

Naming Shapes with Interfaces

lesson 3-1 · ~10 min · 8/26

Quiz

Warm-up from lesson 2-2: you typed an object inline as { name: string; age: number }. What is the drawback of repeating that inline type on five different functions?

interface: declare a shape once

An interface gives an object shape a name you can reuse:

interface User {
  name: string;
  age: number;
}

function greet(user: User): string {
  return "Hello, " + user.name;
}

This is the inline object type from lesson 2-2, extracted and named. Every function that works with users now says User, and the shape lives in exactly one place.

TypeScript checks interfaces structurally: any object with a name string and an age number counts as a User, whether or not it was declared with that intent. The shape is the contract, not the label. This is called structural typing, and it is different from Java-style languages where names matter.

Code exercise · typescript

Run it. Notice the second call passes an object literal directly, it matches the User shape so it type-checks. Then remove the age property from that literal and run again.

Code exercise · typescript

Your turn. Declare interface Song with title (string), artist (string), seconds (number). Write describeSong(song: Song): string returning title + " by " + artist + " (" + seconds + "s)". Print one call with Hey Jude by The Beatles, 431 seconds.