Home > Blockchain >  How to achieve interface polymorphism in Typescript?
How to achieve interface polymorphism in Typescript?

Time:12-16

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:

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?

CodePudding user response:

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"
    }
}
  • Related