Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keyof for static properties of TypeScript classes

Given this code sample in TypeScript playground, I am not able to type properly the greeterBuilderName variable so that it can be passed to getProp utility... keyof Greeter is actually the list of props/methods on instances of Greeter, how can I specify that I want props of the Greeter func itself (prototype, warm_greeter, ... ) ?

In other words, what is the proper type for greeterBuilderName ?

Thanks !

function getProp<T, K extends keyof T>(object: T, property: K): T[K] {
    return object[property];
}

class Greeter {
    private greeting: string;
    public constructor(message: string) {
        this.greeting = message;
    }
    public greet(): string {
        return "Hello, " + this.greeting;
    }
    public static warm_greeter(): Greeter { return new Greeter('good o\' fellow'); }
}

let greeterBuilder: () => Greeter = getProp(Greeter, 'warm_greeter'); // ok
alert(greeterBuilder().greet()); // ok

const greeterBuilderName: keyof Greeter = 'warm_greeter'; // does not build :(
greeterBuilder = getProp(Greeter, greeterBuilderName); // does not build :(
alert(greeterBuilder().greet());
like image 545
halogenr Avatar asked Feb 07 '17 16:02

halogenr


1 Answers

I think you want to get the keys of the Greeter class itself, so

const greeterBuilderName: keyof typeof Greeter = 'warm_greeter';
like image 61
tarling Avatar answered Sep 28 '22 21:09

tarling