0

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

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just to add to this - the generic value <string> can be omitted and TS will still try to guess it. For example new Validator("", "hello") will automatically infer T to be string. Passing an explicit generic argument is still fine but might not be needed in some cases, If you want something like new Validator<"hello" | "world">("", "hello") then you do need to be explicit, however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.