I have a bunch of objects that all have a property with the type of Moment but different names for the key.
I'm trying to write a small utility function using typescript where I can sort any of these objects. Could use some shoving in the right direction.
interface ExampleType1 {
startDate: Moment;
// ... other members
}
interface ExampleType2 {
dueDate: Moment;
// ... other members
}
interface ExampleType3 {
createdAt: Moment;
}
I would expect my function look something like this (half pseudocode):
function sortByDateAsc(data: ATypeThatHasAMoment[], keyName: KeyToTheMomentTypeWithinATypeThatHasAMoment) {
return data.sort((a, b) => {
// whatever sort logic i use here
// accessing the Moment object via a[keyName] and b[keyName]
}
}
I've been fiddling with something like this
function sortByDateAsc<T, K extends keyof T>(data: T[], dateKey: K);
Though within the function T[K] doesn't have a type? I'm not sure how to tell the function "T[K] has to be of type Moment"