Search code examples
typescriptabstract-class

How to infer a constructor param type inside of an abstract class


I have a method in a base abstract class that should return the same type of the constructor parameter. I'm not sure if this is possible or if it even makes sense (maybe I'm missing something obvious).

Here's a simplified version of what I'm trying to do:

abstract class ValueObject {
  private value: any;

  constructor(value: any) {
    this.value = value;
  }

  getValue() {
    return this.value;
  }
}

class UserName extends ValueObject {
  constructor(name: string) {
    super(name);
  }
}

new UserName('some name').getValue(); // This has a type 'any', I want it to be the same type as I called super() with, in this case 'string', but could be any other type for different subclasses 

It makes sense to me in my mind since I can't really instantiate the abstract class, so I need to have a way of passing the type that the method will return.

Is it possible? Does it make sense at all? Should I maybe go for a complete different approach?

Thanks!


Solution

  • You can use generics to specify the type in the abstract class i.e.

    abstract class ValueObject<T> {
      private value: T;
    
      constructor(value: T) {
        this.value = value;
      }
    
      getValue() : T {
        return this.value;
      }
    }
    
    class UserName extends ValueObject<string> {
      constructor(name: string) {
        super(name);
      }
    }
    
    const result = new UserName('some name').getValue();
    console.log(result);
    console.log(typeof(result));