define a interface of ineterfaces in typescript

index.ts
interface IParent {
    name: string;
    child: IChild;
}

interface IChild {
    age: number;
    toys: IToy[];
}

interface IToy {
    name: string;
    type: string;
}

173 chars
16 lines

In the above example, IParent is an interface of interfaces. It has a property called child which is of type IChild, and IChild has a property called toys which is an array of IToy objects.

To use these interfaces, you can create an object like this:

index.ts
const parent: IParent = {
    name: 'John',
    child: {
        age: 5,
        toys: [
            { name: 'car', type: 'vehicle'},
            { name: 'doll', type: 'toy'}
        ]
    }
};
194 chars
11 lines

You can also use declaration merging to add more properties to an existing interface like so:

index.ts
interface IParent {
    gender: string;
}

interface IChild {
    gender: string;
}

interface IToy {
    price: number;
}

interface IParent {
    child: IChild & { gender: string };
}

interface IChild {
    toys: IToy[];
}

const parent: IParent = {
    name: 'John',
    gender: 'Male',
    child: {
        age: 5,
        gender: 'Female',
        toys: [
            { name: 'car', type: 'vehicle', price: 19.99},
            { name: 'doll', type: 'toy', price: 9.99}
        ]
    }
};
494 chars
33 lines

In the above example, we first define gender property for IParent, IChild, and IToy interfaces. Then, we use declaration merging to add gender property to IChild interface and merge it with IParent child property. We also add price property to IToy interface. Finally, we create an object parent using these interfaces with additional gender and price properties added.

gistlibby LogSnag