在typescript中,我们可以使用这样的索引类型:
interface Dummy {
name: string;
birth: Date;
}
function doSomethingOnProperty<T, K extends keyof T>(o: T, name: K): void {
o[name]; // do something, o[name] is of type T[K]
}
var dummy = { name: "d", birth: new Date() };
doSomethingOnProperty(dummy, "name");
问题:
如何添加通用约束以仅接受某种类型的属性名称(是否可能?):
// Generic constraint on T[K] ? T[K] must be of type Date
function doSomethingOnDATEProperty<T, K extends keyof T>(o: T, name: K): void {
o[name];
}
// should not compile,
// should accept only the name of propery "birth" which is of type date
doSomethingOnDATEProperty(dummy, "name");
答案 0 :(得分:5)
您可以执行以下操作:
function doSomethingOnDATEProperty<T extends { [P in K]: Date }, K extends keyof T>(o: T, name: K): void {
let d = o[name]; // do something, o[name] is of type T[K] but also Date
d.getFullYear(); // Valid
}
var dummy = { name: "d", birth: new Date() };
doSomethingOnDATEProperty(dummy, "birth");