Objects and unions

Describe an object shape

Name the properties an object must have and let TypeScript check object literals and property access.

Most of the values your programs pass around are objects. An object type describes the properties your code expects:

type User = {
  id: number
  name: string
}

const user: User = { id: 1, name: 'Ada' }

Once the shape has a name, TypeScript checks every use of it. It rejects a missing name, a string id, or an extra property on a directly checked object literal.

Leave out name and you get:

Property 'name' is missing in type '{ id: number; }' but required in type 'User'.

Add a property the type does not declare and you get:

Object literal may only specify known properties, and 'email' does not exist in type 'User'.

That second error only fires on object literals assigned directly to the type. It catches typos like nmae at the moment you write the object, which is exactly when they are cheapest to fix.

Structural typing

The check is structural. A value does not need to be created by a User constructor. It only needs compatible properties. If a function returns { id: 7, name: 'Grace' }, that value is a valid User, no matter where it came from.

This makes ordinary JavaScript objects easy to type:

function printUser(user: User) {
  console.log(`${user.id}: ${user.name}`)
}

Inside the body, user.id is a number and user.name is a string. A typo like user.fullName fails immediately instead of printing undefined at runtime.

What the type does not do

The function promises to use the User shape. It does not validate unknown runtime input. If the object came from JSON.parse() or a network response, the annotation is a claim, not a check. Later in the course we validate uncertain data before trusting it.

My advice is to keep object types focused on the contract you need. A large type containing every possible API field makes functions harder to reuse. If printUser() only reads id and name, a two-property type is the honest contract.

Exercise: add an active: boolean property. Fix every error without using an assertion.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →