基于属性值的Typescript类属性类型

aiazj4mn  于 2023-05-08  发布在  TypeScript
关注(0)|答案(1)|浏览(173)

是否有可能让Typescript基于另一个属性的值来知道另一个属性的类型(如果另一个属性具有有限数量的值)。
例如,我有一个这样的类:

type AnimalType = 'dog' | 'cat' | 'fish';

class Animal {
    protected data: DogEntity | CatEntity | FishEntity;
    protected type: AnimalType;

    constructor(type: AnimalType, data: DogEntity | CatEntity | FishEntity) {
        this.type = type;
        this.data = data;
    }

    getAge() {
        switch(this.type) {
            case 'dog':
                // Here typescript knows that data is a DogEntity
                break;
            case 'cat':
                // Here typescript knows that data is a CatEntity
                break;
            ...
        }
    }
}

有没有一种方法可以让Typescript根据type的值知道data的类型?类似于:

  • 如果type == dog,则dataDogEntity
  • 如果type == cat,则dataCatEntity
  • 如果type == fish,则dataFishEntity

谢谢!

bf1o4zei

bf1o4zei1#

是的,TypeScript有一种方法可以做到这一点:

type AnimalType = 'dog' | 'cat' | 'fish'

class Animal {
    data: DogEntity | CatEntity | FishEntity
    type: AnimalType

    // ... other code goes here
}

class Dog implements Animal {
    data: DogEntity
    type: 'dog' = 'dog'
}

// ... and so on for the other entity types

另一种解决方案是使用Assert:

class Animal {
    // ... same code as before

    isDog(animal: Animal): asserts animal.Data is DogEntity {
        return animal.type == 'dog'
    }

    // ... repeat for other entity types
}

相关问题