Lesson 4 of 10

Object interfaces

Goal

Name an object's shape once

01

Explanation

The label function assumes the object it receives has a title and a price, and nothing guarantees that. An interface gives that shape a name once, and it becomes a contract the compiler checks at every call.

The matching here is structural: any object that has the required fields with the right types matches the interface, wherever it came from, so you don't need a class or implements.

An object literal, meaning an object you write directly where it's used, gets a stricter check: an extra field in it is an error, because it's usually a slip, like a misspelled name or a field nobody will ever read. This check applies only to object literals, though. A variable you already have that carries extra fields passes without complaint.

02

Your task

Define interface Product with title as a string and price as a number, and make it the type of the label parameter.

Checks

6 checks
  1. No type errors
  2. Product has title and price
  3. An extra field in an object literal is an error
  4. A missing field is an error too
  5. label rejects a price given as a string
  6. label returns the right text
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.