小编JAn*_*Man的帖子

区分类的联合

使用 Typescript 3.4,我尝试根据每个子类上的单个只读字段(鉴别器)来区分 Typescript 类的联合;其本身似乎很简单,但我似乎无法解决它。

下面是一个 Playground 的链接,其中 createFruit 方法应该能够采用通用参数来通过鉴别器过滤下一个属性。任何见解将不胜感激;然而,它似乎允许评估从不。

abstract class Fruit {
    abstract readonly fruitType: string;
}

class Banana extends Fruit {
    fruitType = 'banana';
    length = 2;
    color = 'yellow';
}

class Pear extends Fruit {
    fruitType = 'pear';
    roundness = 'very round';
}

class Apple extends Fruit {
    fruitType = 'apple';
    fallOfMan = true;
    hasWorms = true;
}

type KnownFruits = Banana | Pear | Apple;

type FruitTypes = KnownFruits['fruitType'];

type FruitDiscriminator<T extends FruitTypes> = Extract<KnownFruits, …
Run Code Online (Sandbox Code Playgroud)

union discriminated-union typescript

6
推荐指数
1
解决办法
2004
查看次数

标签 统计

discriminated-union ×1

typescript ×1

union ×1