Lesson 4 of 10
Object interfaces
- 11 min
- 6 checks
- 3 hints
- Go to task
Goal
Name an object's shape once
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.
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- No type errors
- Product has title and price
- An extra field in an object literal is an error
- A missing field is an error too
- label rejects a price given as a string
- label returns the right text