Interfaces: Contracts for Objects
6 min read
Welcome back, TypeScript adventurer! πΊοΈ
In the wild world of vanilla JavaScript, objects are like anarchy. You can add properties, delete them, or typo them (user.naem instead of user.name) and JavaScript will just shrug and say, "Sure, whatever, here's undefined."
This leads to the most famous crash in history: Cannot read property of undefined. π₯
Today, we are going to fix that. We are going to bring Law and Order to your code using Interfaces.
1. Defining Object Shapes with Interfaces π
The Problem
Imagine you are writing a function that expects a User object. In JavaScript, you just have to hope the object passed in has an email and id.
// Vanilla JS - Fingers crossed! π€
function sendEmail(user) {
console.log("Sending to " + user.emial); // Typo! No error until you run it.
}The Solution: The Interface
An Interface is a syntactical contract that the entity must adhere to. It defines the "shape" of the data. It tells TypeScript: "Hey, any object that claims to be a User MUST have exactly these properties with these specific types."
If the object doesn't match the interface, the code won't compile. No runtime explosions.
Syntax & Usage
You define an interface using the interface keyword, followed by the name (usually PascalCase).
// 1. Define the Contract
interface User {
id: number;
username: string;
isActive: boolean;
}
// 2. Use the Contract
const createNewUser = (user: User) => {
// TypeScript knows 'user' has .id, .username, and .isActive
console.log(`Creating user: ${user.username}`);
};
// β
Valid Object
const validUser = {
id: 1,
username: "coder_123",
isActive: true
};
createNewUser(validUser);
// β Error: Property 'isActive' is missing
const badUser = {
id: 2,
username: "hacker_404"
};
// createNewUser(badUser); // TS Error: Argument of type... is not assignable to parameter of type 'User'.π§ Under the Hood (Type Erasure)
Here is a fun fact to impress your friends at parties (or just your rubber duck π¦): Interfaces are ghosts. π»
TypeScript interfaces exist only during development. When you compile your TS code to JavaScript, the interfaces are completely removed (erased). They add zero weight to your final bundle size. They are strictly for the compiler to yell at you if you make a mistake.
2. Optional (?) and Readonly Properties π‘οΈ
The Problem: Optional
Sometimes, data is flexible. If you are building a Profile, not everyone enters their phoneNumber. If you require it in the interface, you force users to send dummy data, which is bad practice.
The Solution: The ? Operator
By adding a question mark ? after the property name, you tell TypeScript: "This property might be here, or it might be undefined. Don't panic if it's missing."
interface UserProfile {
username: string;
email: string;
phoneNumber?: string; // π Optional!
}
const userA: UserProfile = {
username: "alice",
email: "[email protected]"
// No phone number? No problem.
};
const userB: UserProfile = {
username: "bob",
email: "[email protected]",
phoneNumber: "555-0199" // Also valid.
};The Problem: Readonly
In a database, a Primary Key (ID) usually never changes after creation. In your app, you want to ensure that no developer accidentally writes code that overwrites an ID.
The Solution: readonly
The readonly modifier makes a property immutable after the object is created.
interface DatabaseConfig {
readonly dbName: string; // π Can't touch this
timeout: number;
}
const db: DatabaseConfig = {
dbName: "Production_DB",
timeout: 5000
};
db.timeout = 10000; // β
Allowed
// db.dbName = "Test_DB"; // β Error: Cannot assign to 'dbName' because it is a read-only property.Industry Tip: Use
readonlyfor properties andconstfor variables.
3. Extending Interfaces: Building Complex Shapes ποΈ
The Problem
Software development adheres to DRY (Don't Repeat Yourself).
Imagine you have a BasicUser, a Moderator, and an Admin.
BasicUserhas:id,name.Moderatorhas:id,name,permissions.Adminhas:id,name,permissions,sudoAccess.
Copy-pasting id and name everywhere is tedious and error-prone.
The Solution: extends
Just like in Object-Oriented Programming (OOP) or real-life genetics π§¬, interfaces can inherit properties from other interfaces.
interface BasicUser {
id: number;
name: string;
}
// Moderator inherits everything from BasicUser + adds permissions
interface Moderator extends BasicUser {
permissions: string[];
}
// You can extend multiple interfaces!
interface AuditLog {
createdAt: Date;
}
// SuperAdmin has User traits AND Audit traits
interface SuperAdmin extends Moderator, AuditLog {
sudoMode: boolean;
}
const admin: SuperAdmin = {
id: 99, // from BasicUser
name: "Root", // from BasicUser
permissions: ["ban"], // from Moderator
createdAt: new Date(), // from AuditLog
sudoMode: true // from SuperAdmin
};This makes your code modular. If you change the type of id in BasicUser, it updates for everyone automatically. Magic. β¨
4. Index Signatures for Dynamic Objects ποΈ
The Problem
Sometimes you don't know the names of the properties ahead of time.
Imagine you are storing a cache of user sessions, or a dictionary of translations.
- Key:
session_id_123-> Value:UserObject - Key:
session_id_456-> Value:UserObject
You can't write interface Cache { session_id_123: User ... } because the IDs are dynamic.
The Solution: Index Signatures
This syntax describes the types of the keys and values, rather than the specific names.
interface StringDictionary {
[key: string]: string;
// "Any property name (that is a string) must have a string value"
}
const translations: StringDictionary = {
"greeting": "Hello",
"farewell": "Goodbye",
"confusion": "Huh?",
// "count": 42 // β Error: Type 'number' is not assignable to type 'string'.
};Real World Example: API Responses
Often used when handling messy JSON responses where keys vary.
interface SalaryMap {
[employeeId: string]: number; // Key is ID, Value is Salary
}
const salaries: SalaryMap = {
"emp_001": 50000,
"emp_002": 75000,
};β οΈ Warning: Don't overuse Index Signatures. They weaken type safety because they allow any property name. Only use them when the shape of the object is truly dynamic.
π§± Industry Standards & Best Practices
Interface vs. Type:
You will seetype User = { ... }used similarly tointerface User { ... }.- Use
interfacefor objects, API responses, and anything that defines a "shape". Interfaces generally provide better error messages and performance in the compiler. - Use
typefor Unions (string | number), Primitives, or Tuples.
- Use
Naming Conventions:
In the old days (C#/Java era), people prefixed interfaces withI, likeIUser.
Modern TypeScript Standard: Do not use theIprefix. It's considered hungarian notation and unnecessary. Just name itUser.One Interface, One File (Usually):
For large projects, keep your shared interfaces in atypesfolder or alongside the component that uses them.
π References & Further Reading
- Official TypeScript Docs: Interfaces
- TypeScript Deep Dive: Interfaces
- Differences Between Type and Interface
Happy coding! Go define some shapes! π₯ π΅ πΊ
Challenge
Your task is to model the data structures for a simplified Content Management System (CMS) using TypeScript interfaces. You need to define a set of related interfaces that build upon each other to represent different types of content.
Create a base interface named
ContentItem. It should include the following properties:id: A number that cannot be changed after it's assigned.title: A string.createdAt: ADateobject representing when the item was created.
Create an
Articleinterface that inherits fromContentItem. It should have these additional properties:authorId: A number.body: A string containing the main content of the article.tags: An array of strings. This property should be optional.
Create a
Videointerface that also inherits fromContentItem. It must include:sourceUrl: A string pointing to the video file.durationInSeconds: A number.subtitles: An optional object that maps language codes (e.g., "en", "es") to subtitle file URLs. This should be implemented using an index signature where both the key and the value are strings.
Finally, create a
FeaturedArticleinterface. This should extend theArticleinterface and add one more required property:featuredImage: A string containing the URL for a large banner image.
Expected result
Your code should consist of four TypeScript interface definitions that correctly model the CMS structure.
ContentItem: An interface with three properties:id:readonly numbertitle:stringcreatedAt:Date
Article: An interface thatextends ContentItem. It adds three more properties:authorId:numberbody:stringtags:string[](marked as optional with?)
Video: An interface thatextends ContentItem. It adds three more properties:sourceUrl:stringdurationInSeconds:numbersubtitles: An optional property with an index signature of[key: string]: string;.
FeaturedArticle: An interface thatextends Articleand adds one required property:featuredImage:string