Looking to sort an array of items, each with properties of either string or number type, without mixing types for each property:
type Item = {
prop1: string;
prop2: number;
prop3: string;
prop4: number;
}
To keep it abstract, I am using propertyName: keyof Item
to specify which property to sort by. In my sorting function, I access property values like this:
items.sort((item1, item2) => {
const value1 = item1[propertyName];
const value2 = item2[propertyName];
...
both value1 and value2 can be of type string | number
, but I need to differentiate between sorting by string and number properties. TypeScript does not automatically infer that the same property for any item is of the same type, leading to the need for type checking logic. I am exploring the most elegant way to perform type checks based on the property types in the Item itself rather than the actual values, like "if the type of property (propertyName) in Item is 'string' then ..."
Any suggestions on how to achieve this would be greatly appreciated. Thank you!