【问题标题】:TypeScript "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type"TypeScript“算术运算的左侧必须是'any'、'number'、'bigint'或枚举类型”
【发布时间】:2020-12-30 14:00:06
【问题描述】:

我有这个接口的对象数组

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


【解决方案1】:

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
       });
    };

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    相关资源
    最近更新 更多