Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 96 ยท Basic Types

Object Types

Learn TypeScript object types - inline shapes, optional and readonly properties, nested objects, methods, excess property checks and index signatures.

Most data in a real program lives in objects: a user with a name and an email, an order with items and a total, a settings object with a dozen flags. In JavaScript you find out an object is missing a property when your code crashes at runtime with Cannot read properties of undefined. In TypeScript you describe the shape of an object once, and the compiler checks every place that creates or reads it.

An object type lists property names and their types. It says nothing about classes or constructors: any value with the right properties fits. This idea is called structural typing, and it's one of the biggest differences between TypeScript and languages like Java or C#.

This lesson covers inline object types, optional and readonly properties, methods, the "excess property check" that catches typos, and a first look at objects used as dictionaries. If you want to review how objects behave at runtime first, see objects in the JavaScript course.

Writing an object type

An object type looks like an object literal, but with types where the values would be. Separate the properties with semicolons (commas work too):

TypeScript An object type annotation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at the last two calls. book has three properties, but describe only asks for two, and the call is accepted. A value fits an object type if it has at least the listed properties with compatible types. Extra properties are allowed when the value comes from a variable (we'll see the exception for fresh literals shortly).

As with arrays, you often don't need the annotation at all. const book = { title: '...', pages: 312 } is inferred as { title: string; pages: number }. Annotate when you want TypeScript to check that the object matches a shape you designed, and always annotate function parameters, because TypeScript can't infer those.

Writing the same shape twice gets tedious fast. In practice you give it a name with a type alias or an interface:

TypeScript
type Book = { title: string; pages: number; inStock: boolean };

function describe(item: Book): string { /* ... */ }

We'll use inline types in this lesson to keep the focus on the object type syntax itself, and a few aliases where they make examples shorter.

Property errors

When an object doesn't match, the error messages are precise. A missing property, a wrong type and reading a property that doesn't exist are three different errors:

TypeScript Shape mismatches (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(1,7): error TS2741: Property 'age' is missing in type '{ name: string; }' but required in type '{ name: string; age: number; }'.
main.ts(3,63): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(5,18): error TS2339: Property 'email' does not exist on type '{ name: string; age: number; }'.

TS2741 ("property is missing") and TS2339 ("property does not exist") are two of the errors you'll see most often. TS2339 is what catches typos like user.nmae before they become undefined at runtime.

Optional properties

Not every property is always present. Add ? after the name to make a property optional:

TypeScript
{ name: string; nickname?: string }

Inside the code, an optional property's type includes undefined: reading nickname gives string | undefined. That means TypeScript makes you check before you use it as a string.

TypeScript Working with optional properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is the three labels, then undefined (no phone) and 11. The ?? operator and ?. optional chaining are JavaScript features that pair perfectly with optional properties; see nullish coalescing and optional chaining for a refresher.

Now see what happens if you forget the check:

TypeScript Using an optional property unchecked (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(2,10): error TS18048: 'c.nickname' is possibly 'undefined'.

TS18048 is the strict null check doing its job. Without it, this code would crash at runtime with a TypeError. Fix it with a check (if (c.nickname)), a fallback (c.nickname ?? c.name) or optional chaining (c.nickname?.slice(0, 2), which makes the result string | undefined).

Optional vs | undefined

phone?: string and phone: string | undefined look similar, but they aren't the same:

  • phone?: string means the property may be left out entirely.
  • phone: string | undefined means the property must be present, but its value may be undefined.
TypeScript
type A = { phone?: string };
type B = { phone: string | undefined };

const a: A = {};                     // OK
const b: B = {};                     // error TS2741: Property 'phone' is missing
const b2: B = { phone: undefined };  // OK

Use ? for the usual "might not be there" case. Use | undefined when you want every caller to think about the property and pass it explicitly. (The option exactOptionalPropertyTypes goes one step further and forbids writing { phone: undefined } into an optional property; Strict Mode Explained shows it.)

Readonly properties

Mark a property readonly and TypeScript rejects any assignment to it after the object is created. It's perfect for IDs, creation dates and anything that shouldn't change:

TypeScript readonly properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output shows the order with status: 'paid' and items: [ 'tea', 'honey' ]. Remove the // before the last assignment and the run stops with the TS2540 error from the comment.

Two things to remember about readonly:

  1. It's shallow. A readonly items: string[] property can't be replaced with another array, but you can still push into the array. For that you'd write readonly items: readonly string[].
  2. It's compile-time only, like readonly arrays in Arrays and Tuples. The emitted JavaScript is a normal object. Readonly and Immutability covers deep readonly types and Object.freeze().

The status: 'open' | 'paid' | 'shipped' line is a union of literal types: the status can only be one of those three strings. You'll learn this pattern in Literal Types and as const.

Nested objects and methods

Property types can be anything, including other object types, arrays and functions. A method can be written in two ways that mean nearly the same:

TypeScript
type Counter = {
  count: number;
  increment(): void;          // method syntax
  reset: () => void;          // property holding a function
};
TypeScript Nested shapes and methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that the greet method in the object literal doesn't annotate greeting. TypeScript already knows from Customer that it's a string. That's contextual typing: the expected type flows into the literal. You'll use it constantly with callbacks too (see Function Types and Callbacks).

Excess property checks

Earlier you saw that extra properties are fine when you pass a variable. Fresh object literals are different. When you write an object literal directly where a specific type is expected, TypeScript reports any property the type doesn't know about. This is called an excess property check, and it exists to catch typos:

TypeScript Excess properties in literals (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(7,39): error TS2561: Object literal may only specify known properties, but 'tittle' does not exist in type 'Options'. Did you mean to write 'title'?
main.ts(9,54): error TS2353: Object literal may only specify known properties, and 'color' does not exist in type 'Options'.

Without this check, the misspelled tittle would be silently ignored and the window would have no title, a bug that's surprisingly hard to spot. TypeScript even suggests the property you probably meant (TS2561).

The check only applies to fresh object literals. If the object comes from a variable, the normal "at least these properties" rule applies:

TypeScript When excess properties are allowed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints (1, 2), (5, 8) and [ 'x', 'y', 'label' ]. The rule makes sense: a fresh literal is used only in that one place, so an unknown property there is almost certainly a mistake. A variable may be used elsewhere where those extra properties matter. Type Compatibility and Variance explores the full assignability rules.

Because extra properties can sneak through variables, never assume an object has only the properties in its type. That matters when you copy all keys with Object.keys(), spread an object into a database row, or send it as JSON: the extras come along.

Objects as dictionaries: a first look

Sometimes you don't know the property names in advance: a word count, a cache keyed by ID, a set of HTTP headers. Listing the properties isn't possible, so TypeScript offers an index signature that says "any string key maps to this type":

TypeScript
const wordCounts: { [word: string]: number } = {};
wordCounts['hello'] = 1;
wordCounts.world = 2;

The shorter way to write the same thing is the built-in Record type:

TypeScript
const wordCounts: Record<string, number> = {};

Record<K, V> also accepts a union of specific keys, such as Record<'small' | 'medium' | 'large', number>, which requires all three keys to be present. Index signatures, Record, number keys, and when to use a Map instead are the topic of the next lesson, Index Signatures and Record.

Avoid the object and {} types

You may see two vague types in older code:

  • object means "any non-primitive value". It lets you pass an object, but you can't read any properties from it.
  • {} (an empty object type) means "any value except null and undefined", which includes strings and numbers. It almost never means what people expect.
TypeScript
const a: {} = 42;          // allowed, surprisingly
const b: object = { x: 1 };
// b.x;                    // error TS2339: Property 'x' does not exist on type 'object'.

Describe the properties you actually need instead. If you truly accept "anything", use unknown, which any, unknown, never and void explains.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Does const p: { x: number } = { x: 1, y: 2 }; compile?

    Fresh object literals assigned to a typed target get an excess property check, so y is reported (TS2353). Assigning a variable with a y property would be fine.
  2. 2. Given type C = { phone?: string }, what is the type of c.phone when you read it?

    An optional property may be missing, so reading it gives string | undefined under strictNullChecks.
  3. 3. Which object is valid for type B = { phone: string | undefined }?

    The property is required but may hold undefined. {} is missing it, null isn't string | undefined, and mobile is an unknown property.
  4. 4. With type T = { readonly tags: string[] } and const t: T = { tags: [] }, which line compiles?

    readonly is shallow. You can't replace the array, but you can still push into it. Use readonly string[] to block that too.
  5. 5. What does TS2339 usually mean?

    TS2339 "Property 'x' does not exist on type ..." is reported when you access a property the type doesn't know about, which catches typos.

Summary

  • An object type lists property names and types: { name: string; age: number }. Any value with at least those properties fits (structural typing).
  • Name reusable shapes with a type alias or an interface; always annotate object parameters.
  • name?: T makes a property optional, and reading it gives T | undefined. name: T | undefined is required but may hold undefined.
  • readonly blocks reassignment of a property at compile time. It's shallow and has no runtime effect.
  • Properties can be nested objects, arrays or methods; contextual typing types method parameters inside literals.
  • Fresh object literals get an excess property check that catches typos (TS2353, TS2561). Values from variables may carry extra properties.
  • For unknown keys, use an index signature { [key: string]: T } or Record<string, T>. Avoid the vague object and {} types.

Next: Index Signatures and Record