2

I have an abstract class

export abstract class ABaseModel {
  public static isKeyOf<T>(propName: (keyof T)): string {
    return propName;
  }
}

And another class that extends it

export class Model extends ABaseModel {

  public id: number;
  public uid: string;
  public createdByUid: string;
}

To check if a string is a valid property of that class, I have to wirte

Model.isKeyOf<Model>('id');

But I want to write

Model.isKeyOf('id');

Isn't it possible with Type Inference?

1 Answer 1

3

This seems to work:

abstract class ABaseModel {
    public static isKeyOf<T>(this: { new(): T }, propName: (keyof T)): string {
        return propName;
    }
}

Model.isKeyOf("id"); // ok
Model.isKeyOf("name"); // error: Argument of type '"name"' is not assignable to parameter of type '"id" | "uid" | "createdByUid"'

(code in playground)

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

3 Comments

Getting error: The 'this' context of type 'typeof Model' is not assignable to method's 'this' of type 'new () => Model'.
What's the signature of your Model class? It should be the same, for example if it's class Model { constructor(a: string, b: number) { ... } } then you should use: (this: { new(a: string, b: number): T }
The constructor is constructor(props: any[]) { super(); Object.assign(this, props); } So it works with public static isKeyOf<T>(this: { new ({ }): T }, propName: (keyof T)): string { return propName; } Great, thanks a lot!

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.