Home > Mobile >  Extend a base class and narrowing propery type
Extend a base class and narrowing propery type

Time:01-24

For example I have a base class representing an animal owner :

abstract class AnimalOwner {
    public name: string;
    public animal: Animal;
}
type Animal = {
    type: Dog | Cat | Fish,
    foo: string,
    bar: string,
};

Then I have a class that extends this base class but need to narrow the type of animal property to only Dog :

class DogOwner extends AnimalOwner {
    // Here animal.type should be only Dog
}

I'm not sure how to declare it on the DogOwner class...

CodePudding user response:

You can use a generic for that :

enum AnimalType {
    Dog, Cat, Fish
}

abstract class AnimalOwner<T extends AnimalType> {
    public name!: string;
    public animal!: Animal<T>;
    type!: T;
}
type Animal<T extends AnimalType> = {
    type: T
    foo: string,
    bar: string,
};

class DogOwner extends AnimalOwner<AnimalType.Dog> {}

const dog = new DogOwner().animal.type
//    ^? AnimamType.Dog

Playground

  • Related