Bitpath

Lesson 2 · Unit 04

Objects and their types

Named values, and shapes the compiler checks

13 exercisesabout 3 min

What you practise

  • Object literals, type and interface, optional properties, nesting, destructuring, spread, the misspelt property the compiler catches

Try a question from this lesson

Pick one

Curly brackets can group values and give each one a name. What do you think this prints?

TypeScript
const pet = { name: "Rex", age: 3 };
console.log(pet.age);

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Objects

An object groups values that belong together. Each value has a name, its property. Write name: value pairs in curly brackets, with commas between them.

Read a property with a dot, and change it by storing into it.

The compiler works out the type of the object: here, a name that is a string and an age that is a number.

TypeScript
const pet = { name: "Rex", age: 3 };
pet.age = 4;            // change
console.log(pet.name);  // Rex
console.log(pet.age);   // 4

Concept

Naming a shape

type gives the shape of an object a name. After that, the name works as a type, like number or string.

A variable annotated with Pet must hold an object with exactly these properties, each of the right type.

interface Pet { ... } does the same job for objects. You will meet both.

TypeScript
type Pet = {
  name: string;
  age: number;
};
const rex: Pet = { name: "Rex", age: 3 };
const tom: Pet = { name: "Tom", age: 7 };
console.log(rex.name, tom.age); // Rex 7

Concept

Destructuring and spread

Destructuring pulls properties out into variables of the same name, in one line.

Spread, written as three dots, copies all the properties of an object into a new object. Properties written after it replace the copied ones.

Spread gives you a changed copy. The original object stays as it was.

TypeScript
const user = { name: "Ada", age: 36 };
const { name, age } = user;
console.log(name, age);    // Ada 36
const older = { ...user, age: 37 };
console.log(older.age);    // 37
console.log(user.age);     // 36

9 more exercises in the app

  • 3× multiple choice
  • 1× fill the blanks
  • 3× type the answer
  • 1× true or false
  • 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