Learn TypeScript Β· 4/14

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.

javascript
// 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).

typescript
// 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."

typescript
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.

typescript
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 readonly for properties and const for 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.

  • BasicUser has: id, name.
  • Moderator has: id, name, permissions.
  • Admin has: 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.

typescript
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.

typescript
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.

typescript
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

  1. Interface vs. Type:
    You will see type User = { ... } used similarly to interface User { ... }.

    • Use interface for objects, API responses, and anything that defines a "shape". Interfaces generally provide better error messages and performance in the compiler.
    • Use type for Unions (string | number), Primitives, or Tuples.
  2. Naming Conventions:
    In the old days (C#/Java era), people prefixed interfaces with I, like IUser.
    Modern TypeScript Standard: Do not use the I prefix. It's considered hungarian notation and unnecessary. Just name it User.

  3. One Interface, One File (Usually):
    For large projects, keep your shared interfaces in a types folder or alongside the component that uses them.


πŸ“š References & Further Reading

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.

  1. 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: A Date object representing when the item was created.
  2. Create an Article interface that inherits from ContentItem. 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.
  3. Create a Video interface that also inherits from ContentItem. 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.
  4. Finally, create a FeaturedArticle interface. This should extend the Article interface 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.

  1. ContentItem: An interface with three properties:

    • id: readonly number
    • title: string
    • createdAt: Date
  2. Article: An interface that extends ContentItem. It adds three more properties:

    • authorId: number
    • body: string
    • tags: string[] (marked as optional with ?)
  3. Video: An interface that extends ContentItem. It adds three more properties:

    • sourceUrl: string
    • durationInSeconds: number
    • subtitles: An optional property with an index signature of [key: string]: string;.
  4. FeaturedArticle: An interface that extends Article and adds one required property:

    • featuredImage: string
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.