Moshe Shaham
Moshe Shaham

Reputation: 15984

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:

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?

Upvotes: 1

Views: 120

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

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

Upvotes: 3

Related Questions