I have this simple function for sorting objects by date. But currently I have to check if the field actually is a date, before doing the comparison. Is there a way to limit K
to only allow keys that are of a certain type, in this case Date
?
const compareDate = <T, K extends keyof T>(key: K) => (x: T, y: T) => {
const v = x[key];
const w = y[key];
return v instanceof Date && w instanceof Date ? v.getTime() - w.getTime() : 0;
};
list.sort(compareDate('dateField'));
What I would want is:
const compareDate = <T, K extends ???>(key: K) => (x: T, y: T) => {
// ts should know and only allow x[key] and y[key] to be of type Date here:
return x[key].getTime() - y[key].getTime();
}
const list = [{a: 1, b: 'foo', c: new Date}];
list.sort(compareDate('a')); // <-- ts should refuse this
list.sort(compareDate('b')); // <-- ts should refuse this
list.sort(compareDate('c')); // <-- ts should allow this
Is there a way to express this in Typescript