I'm currently facing a challenge while trying to develop a function that arranges an array of objects based on a specific object key. TypeScript keeps throwing an error indicating that the object type is not "any", "number", "bigint" or an "enum". I attempted to restrict the type of the key to only accept number
. Surprisingly, it partially functions when invoking the function, as in cases where the argument contains a property that is not a number, an error message pops up.
Argument of type '"b"' is not compatible with parameter of type 'KeysOfType<{ a: number; b: string; c: number; }, number>'.ts(2345)
Nevertheless, I fail to comprehend why TypeScript fails to recognize that the property is indeed a number within the function itself, leading to errors. How can I overcome/resolve this predicament? Could my approach towards typing be incorrect?
Displayed below are the code snippets containing the aforementioned errors:
type KeysOfType<T, KT> = {
[K in keyof T]: T[K] extends KT ? K : never;
}[keyof T];
export function sortArrayByKey<T, K extends KeysOfType<T, number>>(
list: T[],
propertyKey: K
) {
// The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362)
// The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2363)
return list.slice().sort((a, b) => (a[propertyKey] - b[propertyKey]));
}
// works
sortArrayByKey([{a: 1, b: 'asd', c: 3.0}, {a: 2, b: '123', c: 2.1}], 'a');
// Argument of type '"b"' is not compatible with parameter of type 'KeysOfType<{ a: number; b: string; c: number; }, number>'.ts(2345)
sortArrayByKey([{a: 1, b: 'asd', c: 3.0}, {a: 2, b: '123', c: 2.1}], 'b');