While experimenting with this TypeScript playground code sample, I encountered an issue with defining the greeterBuilderName
variable. How can I specify that I want properties of the Greeter function itself (such as prototype
, warm_greeter
, etc.) when keyof Greeter
refers to the properties/methods of instances of Greeter?
In simpler terms, what would be the correct type for greeterBuilderName
to include the properties of the Greeter function?
Thank you for your assistance!
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());