簡體   English   中英

Typescript如何實現接口多態?

[英]How to achieve interface polymorphism in Typescript?

我有這個接口層次結構:

interface parent {
    common: string;
}

interface child1 extends parent {
    prop1: string;
}

interface child2 extends parent {
    prop2: string;
}

現在我想要一個接口,其中一個屬性是parent接口,這意味着它可以是 child1 或 child2。

我試過這個:

interface SomeObject {
    member: parent;
}

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

編譯器抱怨prop1不是parent的成員。

實現這一目標的正確方法是什么?

常見的方法是創建一個通用類型

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM