Course contentsShow
← TypeScript
Lesson 295 of 1,7967. ObjectsFree lesson

Object Literal Type Inference

How TypeScript infers object types from object literal values without explicit annotations.

Object Literal Type Inference

What you'll learn: How TypeScript automatically figures out the shape and types of objects you create, without you writing explicit type annotations.

The Core Idea

When you write an object literal in TypeScript, the compiler inspects the values you've assigned to each property and infers what type that object should be. It looks at each property name and its corresponding value type, then builds a complete object type description on the fly.

Think of it like TypeScript taking a snapshot of your object: "This thing has a name property that's a string, an age property that's a number, and an active property that's a boolean."

How It Works

const user = {
  name: "Alice",
  age: 30,
  active: true
};

TypeScript infers the type:

{
  name: string;
  age: number;
  active: boolean;
}

You didn't write any annotations — TypeScript saw "Alice" (a string), 30 (a number), and true (a boolean) and figured it out.

Nested Objects

Inference works recursively through nested structures:

const config = {
  server: {
    port: 8080,
    hostname: "localhost"
  },
  debug: false
};

TypeScript infers the server property as an object type with its own port (number) and hostname (string) properties.

Why This Matters

Object literal type inference is the foundation of working with objects in TypeScript. It lets you write natural JavaScript while getting automatic type safety. You get all the benefits — autocomplete, error checking, refactoring support — without extra typing work.

Key Takeaway: TypeScript automatically infers object types from the values in object literals, building a complete type description based on each property's value type.