Course contentsShow
← TypeScript
Lesson 172 of 1,7964. Type InferenceFree lesson

Object Literal Context

How assigning to a typed variable provides context for object literal properties and their types.

What You'll Learn

You'll discover how TypeScript uses the target variable's type to understand and check the properties inside an object literal you're assigning to it.


The Core Idea

When you assign an object literal directly to a typed variable, TypeScript doesn't just check if the object matches the type — it uses that type to provide context for the properties inside the object itself.

This is contextual typing in action: the type of the variable flows inward to help TypeScript understand what types the properties should have, enabling better autocomplete and type checking.

How It Works

type User = {
  name: string;
  age: number;
};

const user: User = {
  name: "Alice",  // TypeScript knows this should be string
  age: 30         // TypeScript knows this should be number
};

Notice you didn't have to annotate "Alice" or 30 — TypeScript inferred them as string and number respectively because of the User type context.

Without Context

const userObject = {
  name: "Alice",
  age: 30
};
// TypeScript infers: { name: string; age: number }
// But it doesn't know about User type until you assign

The Benefit

The target type acts like a template that guides TypeScript while you're typing the object literal. You get autocomplete for property names, immediate errors for wrong types, and protection against extra properties.


Key Takeaway: When you assign an object literal to a typed variable, that variable's type provides context that helps TypeScript understand and validate the properties inside the literal.