Can someone help me understand how to avoid using this particular pattern (b[firstCriteria] as number)
? I need the function to be type-safe and only allow passing an existing key from the object inside the array.
I'm encountering an error in TypeScript, and I've come across two potential solutions:
One approach is to include
[key: string]: number
in the type definition, but this allows any key to be passed.interface BaseHighLightsRes { id: number; manager_rank: number; player_name: string; entry_name: string; [key: string]: number; }
The second option involves adding
as Number
.import { BaseHighLightsRes } from "../types/apiResponce"; export const sortHighlight = <T extends BaseHighLightsRes>( array: T[], firstCriteria: keyof T, secondCriteria: keyof T = "manager_rank" ): void => { array.sort( (a, b) => (b[firstCriteria] as number) - (a[firstCriteria] as number) || (a[secondCriteria] as number) - (b[secondCriteria] as number) ); };
I'm uncertain if my type implementation is accurate. How can I ensure that TypeScript correctly infers the type?