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

How to achieve interface polymorphism in Typescript?

I have this interface hierarchy:

interface parent {
    common: string;
}

interface child1 extends parent {
    prop1: string;
}

interface child2 extends parent {
    prop2: string;
}

Now I want to have an interface, which one property is a parent interface, meaning it can be either child1 or child2.

I tried this:

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 SomeObject {
    member: parent;
}

let a: SomeObject = {
    member: {
        common: "a",
        prop1: "b"
    }
}

The compiler complains that prop1 is not a member of parent.

What is the correct way to achieve this?

>Solution :

The common approach to this is to create a generic type:

interface parent {
    common: string;
}

interface child1 extends parent {
    prop1: string;
}

interface child2 extends parent {
    prop2: string;
}

interface SomeObject<T extends parent> {
    member: T;
}

let a: SomeObject<child1> = {
    member: {
        common: "a",
        prop1: "b"
    }
}
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