2. Object Architecture (Interfaces vs Types)
In standard JavaScript, objects are just collections of key-value pairs. You can add, remove, or change properties at any time. In TypeScript, objects are strictly bound to structural contracts known as Interfaces or Type Aliases. These structures dictate exactly what properties an object must have, what types they contain, and whether they can be modified.
Understanding how to architect your data models is the most important skill in TypeScript development.
The interface Keyword
An interface is a blueprint for an object. It defines a rigid shape that an object must conform to.
Rules of Interfaces:
- They strictly apply only to objects (they cannot type a primitive string or union).
- They support Optional Properties using the
?modifier. - They support Read-Only Properties using the
readonlymodifier, preventing mutation after initialization.
interface User { readonly id: string; // Cannot be changed after creation username: string; email: string; age?: number; // Optional: might be undefined } const u1: User = { id: "user_123", username: "alice99", email: "alice@test.com" // 'age' is legally omitted }; // u1.id = "user_456"; // ERROR: Cannot assign to 'id' because it is a read-only property.
Index Signatures (Dynamic Dictionaries)
Sometimes you don't know the exact names of the properties beforehand (like building a cache or a translation dictionary), but you know the types of the keys and values. You handle this using an Index Signature.
interface TranslationDictionary { // Any string key is allowed, but the value MUST be a string [key: string]: string; } const translations: TranslationDictionary = { hello: "bonjour", goodbye: "au revoir", // 123: "cent", // ERROR: Key must be a string (though JS coerces numbers) // count: 5 // ERROR: Value must be a string };
The type Keyword (Type Aliases)
A Type Alias (type) is a more versatile alternative to an interface. While interfaces only describe objects, type can describe objects, primitives, tuples, and unions. It acts as a variable declaration for types.
// Typing a standard object (similar to interface) type Product = { id: number; price: number; }; // Typing Unions (Interfaces CANNOT do this) type Status = "pending" | "shipped" | "delivered"; type ID = string | number; let currentStatus: Status = "pending"; // currentStatus = "lost"; // ERROR: Type '"lost"' is not assignable to type 'Status'.
Composition: Extending vs Intersecting
When building large systems, you compose complex types from smaller ones. Interfaces use extends, while Types use the Intersection operator &.
Interface Extension: Interfaces can inherit from other interfaces. This is highly performant and the preferred method for object composition.
interface BaseEntity { id: string; createdAt: Date; } interface Article extends BaseEntity { title: string; content: string; }
Type Intersections: Type aliases combine structures using the & symbol. This literally merges the properties of both types into a single new type.
type NameTrait = { name: string }; type AgeTrait = { age: number }; // Merging traits together type Person = NameTrait & AgeTrait; const john: Person = { name: "John", age: 30 };
Declaration Merging (The Interface Superpower)
There is one massive behavioral difference between interface and type: Declaration Merging. If you define the exact same interface twice in the same scope, TypeScript will magically merge them together into a single interface. If you try this with a type, it throws a "duplicate identifier" error.
// 1. First declaration interface Window { title: string; } // 2. Second declaration (Merges with the first) interface Window { resize: () => void; } // Resulting Interface: const myWindow: Window = { title: "Main", resize: () => console.log("Resized") }; // ERROR: Duplicate identifier 'MyType'. // type MyType = { a: string; }; // type MyType = { b: number; };
When to use which? The industry standard is to use interface for object definitions (like API payloads and React Props) because they are faster for the compiler to process and support declaration merging. Use type when you need unions, tuples, or complex conditional/mapped types.
Knowledge Check
Ready to test your understanding of 2. Object Architecture (Interfaces vs Types)?