Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically add property with type to interface

I have this interface

interface Base {
    common: {
        foo: string,
    }
}

interface ExtendedOne extends Base {
    count: number,
}

interface ExtendedTwo extends Base {
    origin: string,
}

Now, what I want is via the interface definition of ExtendedOne and ExtendedTwo add another property plus type to the common prop coming from Base.

So lets say (pseudocode)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface ExtendedOne extends Base {
    count: number,
    common: {
        ...Base,
        anotherProp: boolean,
    }
}

interface ExtendedTwo extends Base {
    origin: string,
    common: {
        ...Base,
        anotherProp: number,
    }
}

The prop added will always have the same name (here anotherProp), but the type will be different.

If needed, the interface can be changed to a type.

>Solution :

You can use & operator in Typescript to combine types.

interface Base {
    common: {
        foo: string;
    };
}

interface ExtendedOne extends Base {
    count: number;
    common: Base["common"] & { anotherProp: boolean };
}

interface ExtendedTwo extends Base {
    origin: string;
    common: Base["common"] & { anotherProp: number };
}

TypeScript has some great utility types too. For examples, check Omit and Pick that allow you to selectively create a new type by omitting or picking properties from another type.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading