Skip to the workspace
Pebellslearn by building
TypeScript Types  ›  Lesson

Object Types and Classes

Object 12 minAn object type lists property names with their types, and a class declaration gives you both a constructor and a type of the same name.

typescript / Object Types and Classes

Explore each scene at your own pace.

01 · The rule

The rule

Object Types and Classes

An object type lists property names with their types, and a class declaration gives you both a constructor and a type of the same name.

Describe object fields and class instances without confusing a type with a runtime object.

Our tracker's central value is a task: an object with an id, a title, a done flag and maybe a due date. Describing that shape once, and having the compiler hold every function to it, is where TypeScript starts to pay for itself.

The rule

An object type lists each property and its type; a class is also a type.

Write an object type with braces, listing each property name and its type:

type Task = {
  readonly id: number;    // cannot be reassigned
  title: string;
  done: boolean;
  due?: string;           // optional: may be left out
};

const t: Task = { id: 1, title: "Buy milk", done: false };

t.done = true;   // fine
t.id = 2;        // error: id is a read-only property

Three rules to know:

  • Required by default. Leaving out title is an error: the property is missing.
  • ? makes a property optional. due may be absent, so reading it gives a string or undefined.
  • Excess property check. When you write a fresh object literal where a Task is expected, TypeScript also flags properties the type does not mention, such as priority: 1. Those are usually typos.

You can also name an object shape with an interface, which the final section covers in depth. For now, type Task = {...} and interface Task {...} both describe the same shape.

Avoid the loose types Object, object and {} for data like this. They say almost nothing: you cannot read .title from a value typed object.

Classes. A class declaration creates two things: a constructor you call at runtime, and a type with the same name describing its instances.

class TaskList {
  tasks: Task[] = [];
  add(task: Task): void { this.tasks.push(task); }
}

const inbox: TaskList = new TaskList(); // TaskList used as a type
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.