Using Nested Types and Nested Interfaces in TypeScript

Updated: January 8, 2024 By: Guest Contributor Post a comment

Introduction

Like the intertwined narratives of a Mark Twain novel, TypeScript’s nested types and interfaces elegantly weave together to create robust type definitions and architectural harmony in the grand novel of software development.

Begin at the Beginning: Basic Nesting

Our tale opens not with Tom Sawyer but a ‘House’ interface – unassuming, yet brimming with possibilities.

interface House {
    address: string;
    resident: {
        name: string;
        age: number;
    };
}

As simple as whitewashing a fence, our resident is nested within the House.

The Plot Thickens: Intermediate Structures

Delving deeper into our adventure, we harness the union type as Huck Finn might fashion a raft, contriving a means to navigate amorphously.

interface House {
    address: string;
    resident: Person | Entity;
}

interface Person {
    name: string;
    age: number;
}

interface Entity {
    name: string;
    kind: 'Business' | 'Non-Profit';
}

Suddenly, our narrative accommodates a cast as diverse as Mississippi’s wildlife.

Generics: A Fork in the River

The plot coils as we encounter generics – akin to discovering a hidden cache within a cavern.

interface Repository<T> {
    id: number;
    data: T;
}

interface User {
    username: string;
}

const userRepository: Repository<User> = {
    id: 1,
    data: { username: 'TwainFan' }
};

With the stroke of Clemens’s pen, the Repository is alive, adaptable to any character in his repertoire.

Advanced Enigmas: Recursive Types

As our journey reaches its zenith, we encounter recursive types, spiraling infinitely like the tales from Twain’s own life.

type TreeNode<T> = T & { children: TreeNode<T>[] };

const familyTree: TreeNode<{name: string}> = {
    name: 'Samuel',
    children: [
        {
            name: 'Orion',
            children: [{ name: 'Clara', children: [] }]
        },
        {
            name: 'Henry',
            children: []
        }
    ]
};

Each child a story, every descendant a chapter, the lineage of logic elegantly authored.

Conclusion

In conclusion, our code is but a literary work, and TypeScript’s nested types and interfaces, the finely tuned syntax carrying the narrative. They are the backbone over which we drape our tales of logic and functionality, our adventures in programming. From the simple abode to the generically-encompassing repository, from recursive types to polymorphic enigmas – our expedition through TypeScript has borne fruit aplenty.