鉴于this code sample in TypeScript playground,我无法正确键入greeterBuilderName
变量,以便可以将其传递给getProp实用程序... keyof Greeter
实际上是道具/方法的列表Greeter的实例,如何指定我想要Greeter func本身的道具(prototype
,warm_greeter
,...)?
换句话说,greeterBuilderName
的正确类型是什么?
谢谢!
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());
答案 0 :(得分:8)
我想你想获得Greeter类本身的键,所以
const greeterBuilderName: keyof typeof Greeter = 'warm_greeter';