我有一个带有接口的对象数组
interface Item {
country: string;
cases: number;
deaths: number;
population: number;
}
我想制作分拣功能
const sortDescending = (type: keyof Item): void => {
data.sort((a, b) => {
return a[type] - b[type];
});
};
打字脚本不允许我执行它的问题,因为";算术运算的左侧必须是"any"、"number"、"bigint"或枚举类型";我知道对象中有字符串,不能用它们进行算术运算。如何修复?
Typescript让我们在使用算术时更加深思熟虑,如果乍一看不符合逻辑,就会抛出错误。
const sortDescending = (type: keyof Item): void => {
data.sort((a, b) => {
// add types 'as any' -> or a better type like number | boolean
return (a[type] as any) - (b[type] as any);
// (<any>a[type]) can also be an option
});
};