我有这个简单的函数来按日期对对象进行排序。但目前我必须在进行比较之前检查该字段是否真的是一个日期。在这种情况下,有没有办法限制K
只允许某种类型的键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'));
我想要的是:
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
有没有办法在打字稿中表达这一点