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

When to Extract vs Keep Inline

Guidelines for deciding whether object type literals should remain inline or become named types.

When to Extract vs Keep Inline

You'll learn practical guidelines for deciding when object type literals should become named types versus staying inline.

The Decision Point

TypeScript lets you define object types directly where you use them (inline) or extract them into named types. Both approaches are valid, but choosing wisely affects code readability and maintainability.

Think of it like labeling boxes in your garage. A small box of batteries you use once? No label needed. But if you're constantly grabbing tools from the same box across different projects, give it a clear label.

Keep Types Inline When:

1. The type is used only once

function logUser(user: { name: string; email: string }) {
  // This type appears nowhere else
}

2. The type is very simple

const config: { enabled: boolean } = { enabled: true };

3. The context makes the structure obvious

function processData(options: { verbose: boolean }) {
  // "options" clearly describes what this object is
}

Extract to Named Types When:

1. The type is reused multiple times

type User = { name: string; email: string };

function createUser(data: User) {}
function updateUser(id: number, data: User) {}

2. The type is complex or nested

type UserProfile = {
  name: string;
  contact: { email: string; phone: string };
  preferences: { theme: string; notifications: boolean };
};

3. You want to communicate domain concepts

type Product = { id: number; name: string; price: number };
// "Product" tells readers this is a business entity

Key Takeaway: Extract types when they're reused, complex, or represent important domain concepts. Keep them inline for one-off, simple structures where the context is clear.