Ilja
Ilja

Reputation: 46479

How to inherit class variable type from constructor?

I am writing a validator class, something like

class Validator {
  private path: string;
  private data: unknown;

  constructor(path: string, data: string) {
    this.data = data;
    this.path = path;

  }

  public isString() { /* ... */ }
}

Right now my data is of type unknown, but I'd like type to be inherited from constructor i.e.

const validator = new Validator("HomePage", 123); // data in class should be inherited as number

with functions I usually did something like

function<T>(path: string, data: T) {  }

But I am unable to figure out how to do it with classes. In particular inheriting from constructor

Upvotes: 0

Views: 34

Answers (1)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10137

It's really similar as with functions:

class Validator<T> {
  constructor(private path: string, private data: T) {

  }
}

const validator = new Validator<string>('', '');

Also that's not called inheritance, it's just a generic parameter.

You also shouldn't have private path string, constructor parameters already do that for you.

Upvotes: 2

Related Questions