Anonymous vs Named Object Types
You'll learn when to write object types inline versus giving them a reusable name.
The Core Idea
When typing objects in TypeScript, you have two choices: write the type structure directly where you use it (anonymous), or define it once with a name and reuse it (named). Both describe the same shape, but they differ in reusability, readability, and maintenance.
Think of it like giving directions. You can say "go to the building at 123 Main Street with the red door" every single time (anonymous), or you can say "go to City Hall" after defining it once (named). The destination is the same, but one approach is more efficient when you need to reference it repeatedly.
Anonymous Object Types
These are inline type literals written directly in variable declarations, parameters, or return types:
function greet(user: { name: string; age: number }): void {
console.log(`Hello, ${user.name}!`);
}
let product: { title: string; price: number; inStock: boolean };
Named Object Types (Type Aliases)
Extract the type into a reusable definition:
type User = {
name: string;
age: number;
};
function greet(user: User): void {
console.log(`Hello, ${user.name}!`);
}
let currentUser: User;
let adminUser: User;
When to Choose Each
Use anonymous types for one-off structures that appear only once, especially simple shapes or quick function parameters.
Use named types when:
- The same structure appears in multiple places
- The type is complex and deserves documentation
- You want to communicate intent through the type name
- You need to reference it across files
Key Takeaway: Use anonymous object types for one-time, simple structures; extract to named types (type aliases) when you need reusability, clarity, or the type appears multiple times.