Lesson 2 · Unit 01
Object types
Shapes, not names: structural typing and its one extra check
What you practise
interfaceandtype, optional andreadonlyproperties, structural typing (shape, not name), the excess property check and when it applies
Try a question from this lesson
Pick one
Dog never says it implements Named. What happens?
interface Named { name: string }
class Dog {
name = "Rex";
bark() { return "woof"; }
}
function greet(x: Named) {
return "hi " + x.name;
}
console.log(greet(new Dog()));Correct answer
hi Rex
Why
A Dog has a name: string, and that is all Named asks for. No implements, no inheritance. It is duck typing, the way Python does it, except the compiler checks the duck before the program runs.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Structural typing
A type is a shape: a list of members a value must have. A value fits when it has them all, whatever its class is called and whatever else it carries.
interface and type both name a shape. Python's closest match is typing.Protocol.
interface Point { x: number; y: number }
type Point2 = { x: number; y: number };
const a: Point = { x: 1, y: 2 };
const b: Point2 = a; // same shape: fineConcept
The excess property check
One exception. When you write an object literal right where a type is expected, every property must be known to that type.
Nobody else can ever reach an extra property written there, so it is almost always a typo. Pass the same object through a variable and the check does not apply.
interface Point { x: number; y: number }
const a: Point = { x: 3, y: 4 };
const b: Point = { x: 3, y: 4, z: 9 };
// line 3 is rejected: 'z' is not in Point10 more exercises in the app
- 2× true or false
- 2× fill the blanks
- 2× type the answer
- 3× multiple choice
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.