ppulwey
ppulwey

Reputation: 318

TypeScript - Type Inference with keyof keyword

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?

Upvotes: 2

Views: 555

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

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)

Upvotes: 3

Related Questions