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());
I think you want to get the keys of the Greeter class itself, so
const greeterBuilderName: keyof typeof Greeter = 'warm_greeter';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With