Home > Enterprise >  How should i make method in father class determine is type base on subclass's method in typescr
How should i make method in father class determine is type base on subclass's method in typescr

Time:10-13

I have a code like this.

class Base{
   private getData(): Data | undefined{
        return undefined
   }
   public get output(): Data | undefined {
        return {
             ...//Other outputs
             data: this.getData()
        }
   }
}
class A{
    private getData(){
        return getDatasFromOutside()
    }
}
let x = new A()
x.output.data // Data | undefined

As you can see, typescript think x.output.data is Data | undefined but it actually is just Data.

How to fix this?

CodePudding user response:

You can use some generics to represent this:

abstract class Base {
  public getData(): Data | undefined {
    return undefined
  }
  getOutput<D>(this: {getData(): D}): { data: D } {
    return {
      // ... other outputs
      data: this.getData()
    };
  }
}
class A extends Base {
  public getData(): Data {
    return getDatasFromOutside()
  }
}
let x = new A()
x.getOutput().data // getOutput<Data>(this: A): Data

(playground)

However, this has some limitations:

  • the getData method needs to be public to count as part of the type
  • the output getter must be a method, since TypeScript does not support generics or this types on accessor property declarations

A better alternative would be an abstract base class with two implementations:

abstract class Base<D = undefined> {
  protected abstract getData(): D;
  public get output(): { data: D } {
    return {
      // ... other outputs
      data: this.getData()
    };
  }
}
class A extends Base<undefined> {
  protected getData() {
    return undefined;
  }
}
class B extends Base<Data> {
  protected getData() {
    return getDatasFromOutside()
  }
}
let x = new B()
x.output.data // Data

(playground)

CodePudding user response:

You probably want to declare the method as

abstract protected getData(): Data;

in the Base class, then also make the output getter return Data and never undefined.

  • Related