Skip to content

Instantly share code, notes, and snippets.



Created Sep 16, 2020
What would you like to do?
Sort compare function with key accessor
type FilteredKeys<T, U> = { [P in keyof T]: T[P] extends U ? P : never }[keyof T]
const compare = <T>(fn: (x: T, y: T) => number) => <O extends object>(key: FilteredKeys<O, T>) => (
a: O,
b: O,
): number => {
const valA = (a[key] as unknown) as T
const valB = (b[key] as unknown) as T
return fn(valA, valB)
export const compareStrings = compare<string>((a, b) => a.localeCompare(b))
export const compareDates = compare<Date>((a, b) => a.valueOf() - b.valueOf() )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment