For example, I'd like to add Typescript type safety to the vanilla Javascript Sort array of objects by string property value solution. It accepts as args keys of the object to be sorted, to determine which key to sort by. If the key is prefixed with -
, the sort is reversed.
How would I do type the arg to accept, for example, both "age"
and "-age"
?
This is my attempt:
export function dynamicSortMultiple<T extends object, U extends keyof T>(
props: Array<U>,
) {
function dynamicSort(key: U) {
let sortOrder = 1
if (typeof key === 'string' && key.startsWith('-')) {
sortOrder = -1
}
return function (a: T, b: T) {
const result = a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0
return result * sortOrder
}
}
return function (obj1: T, obj2: T) {
let i = 0
let result = 0
const numberOfProperties = props?.length
while (result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2)
i++
}
return result
}
}
export interface User {
userId: string
firstName: string
lastName: string
login: string
password: string
rank: number
score: number
age?: number
}
dynamicSortMultiple<User, keyof User>(['firstName', 'score', '-age'])
On the last line I see the error
Type '"-age"' is not assignable to type 'keyof User'.
Is there an any way to extend keyof User
properly so that values prefixed with '-' are still considered valid values for the type?
I'll appreciate any solution even if you replace mine entirely.