Bitpath

Lesson 2 · Unit 01

Object types

Shapes, not names: structural typing and its one extra check

13 exercisesabout 3 min

What you practise

  • interface and type, optional and readonly properties, 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?

TypeScript
interface Named { name: string }
class Dog {
  name = "Rex";
  bark() { return "woof"; }
}
function greet(x: Named) {
  return "hi " + x.name;
}
console.log(greet(new Dog()));

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.

TypeScript
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: fine

Concept

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.

TypeScript
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 Point

10 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.

One email when Bitpath is ready to try. Nothing else. Privacy