In typescript, we can use index types like this :
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");
Question :
How to add a generic constraint to only accept name of property of certain type (is it possible ?) :
// 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");
You can do the following:
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");
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