Skip to content

Instantly share code, notes, and snippets.

@MikelArnaiz
Last active September 16, 2020 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikelArnaiz/964f23ab269339f590189c869f3f6986 to your computer and use it in GitHub Desktop.
Save MikelArnaiz/964f23ab269339f590189c869f3f6986 to your computer and use it in GitHub Desktop.
Sort compare curried function to access obj string properties values
// 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