I’m trying to sort items: Item[]
having properties of type ‘string’ or ‘number’ without mixing types for each property:
type Item = {
prop1: string;
prop2: number;
prop3: string;
prop4: number;
}
I want to make it abstract, which property I’m sorting by, so i got: propertyName: keyof Item
I get property values in my sorting function this way:
items.sort((item1, item2) => {
const value1 = item1[propertyName];
const value2 = item2[propertyName];
...
so value1 is string | number
, value2 is string | number
too.
I want to use separate further logic for sorting by properties of type ‘string’ and by properties of type ‘number’, so I need to know the type of the property I’m sorting by. The problem is that TS doesn’t get that the same property for any item is of the same type, so if value1 is a string – value2 either.
I’m trying to find out the most elegant way of types checking without unneeded checks for values, which would preferably be based on the type Item itself, not the values, like: ‘if the type of property (propertyName) in Item is ‘string’ then …’
Thanks for your help.