简体   繁体   中英

The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. Can't declare Number as number

I have an array of objects

student = [{
rollNo: Number,
name: String,
dateOfJoining: Number
}];

Now I'm trying to sort my array inside my function using this code.

students(){
for( let item of res.data){
this.event.push({
        name: item.name,
        rollNo: item.rollNO,
        date: item.joining,
      });
}
this.student.sort((val1, val2) => {return val2.dateOfJoining - val1.dateOfJoining});
}

But I'm getting the error "The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type." I know it's because my dateOfJoining is 'Number' and not 'number'.

But I can't write it as 'number' because then I get the error "'number' only refers to a type, but is being used as a value here."

Number is a constructor for the JavaScript number type. This is not the value that you intend.

interface Student {
  rollNo: number;
  name: string;
  dateOfJoining: number;
}

student: Student[] = [{
  ...
}];

Note that this will require a default value for student , but an empty array will also work, eg

student = Student[] = [];
student.push({ rollNo: 1, name: 'Andrew', dateOfJoining: 2 });

At this point you will have to fill in student with the actual values which should be numbers and strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM