首页 > 解决方案 > 使用泛型扩展 Type1 或 Type2

问题描述

有没有办法在 TypeScript 中type1type2在 TypeScript 中扩展泛型 T?

例如,我有以下内容:

interface Edible { }

interface Fruit extends Edible {
    isFruity: boolean
}
interface Veggie extends Edible {
    isHealthy: boolean;
}
interface Dairy extends Edible {
    isHighProtein: boolean;
}

interface Apple extends Fruit {
    nice: boolean;
    sweet: boolean;
}
// and so on so forth...

现在我想要一个函数来接受 aFruit或的东西,Veggie我该如何实现呢?这是表达“扩展FruitVeggie”的正确方式吗?

function yum<T extends Fruit | Veggie>(thing: T) {
    //...
    if ("isFruity" in thing) {
        thing.isFruity;  // Error: Property 'isFruity' does not exist on type 'T'.
    }
}

此外,如何进一步缩小类型Apple,例如?

function yum<T extends Fruit | Veggie>(thing: T) {
    //...
    if ("isFruity" in thing) {
        thing.isFruity;  // Error: Property 'isFruity' does not exist on type 'T'.

        if ("sweet" in thing) {
            console.log("this is an apple!");
            thing.sweet; // Error: Property 'sweet' does not exist on type 'T'.
        }
    }
}

标签: typescript

解决方案


推荐阅读