Last active
September 16, 2020 07:45
-
-
Save MikelArnaiz/964f23ab269339f590189c869f3f6986 to your computer and use it in GitHub Desktop.
Sort compare curried function to access obj string properties values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/a/61476921/1355416 | |
type FilteredKeys<T, U> = { [P in keyof T]: T[P] extends U ? P : never }[keyof T] | |
const compareStrings = <T extends object>(key: FilteredKeys<T, string>) => (a: T, b: T): number => { | |
const valA = (a[key] as unknown) as string | |
const valB = (b[key] as unknown) as string | |
return valA.localeCompare(valB) | |
} | |
type Example = { | |
x: string | |
y: number | |
z: boolean | |
} | |
const example: Example[] = [ | |
{ | |
x: 'test', | |
y: 42, | |
z: true, | |
}, | |
{ | |
x: 'foo', | |
y: 5, | |
z: false, | |
}, | |
] | |
// Only allows x, no y or z | |
export const foo = example.sort(compareStrings('x')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment