Object Types

Curly Braces With Types

Object Types

Object types describe an object's shape — each property with its own type. The most common type form in TypeScript.

4 min read Level 1/5 #typescript#objects#types
What you'll learn
  • Write an inline object type
  • Use `?` for optional, `readonly` for immutable
  • Tell `{}` and `Record` apart

An object type lists the properties an object has, each with its own type.

Inline Object Types

let user: { name: string; age: number } = {
  name: "Ada",
  age: 36,
};

Semicolons or commas between fields — both work, commas are more common.

In Function Parameters

function greet(user: { name: string; age?: number }) {
  console.log(`Hi, ${user.name}`);
}

age?: number makes age optional — { name: "Ada" } is valid.

Optional and Readonly

type User = {
  readonly id: string;     // can't be reassigned
  name: string;             // required
  age?: number;             // optional
};

We’ll cover ? and readonly in depth in the next chapter. For now, just know the syntax.

Nested Objects

let post: {
  title: string;
  author: {
    name: string;
    email: string;
  };
} = {
  title: "Hi",
  author: { name: "Ada", email: "ada@x.com" },
};

For nesting more than one level, you’ll usually extract to a named type (next lesson but one).

The Empty Object Type {}

{} looks like “an object with no properties”, but its meaning is actually “any value that’s not null or undefined”:

let x: {} = 1;     // ✓
let x: {} = "hi";  // ✓
let x: {} = null;  // ✗

Surprising. For “an object with no known properties”, Record<string, unknown> is usually what you want.

Record for Dynamic Keys

const scores: Record<string, number> = {
  alice: 9,
  bob: 7,
};

Record<K, V> describes an object with keys of type K and values of type V. Use it when you don’t know the specific keys at type time but they all share a value type.

Excess Property Checks

When you pass an object literal directly, TS checks for unknown properties:

type User = { name: string };

const u: User = { name: "Ada", extra: 1 };
//                                ~~~~~ Object literal may only specify known properties.

This catches typos in field names. The check applies to object literals; passing a variable doesn’t trigger it.

Up Next

When to annotate explicitly, and when to let inference do the work.

Annotations →