43
votes
1    interface Dimensions {
2        width: Number,
3        height: Number
4    }
5
6    function findArea(dimensions: Dimensions): Number {    
7        return dimensions.height * dimensions.width;
8    }

line 7, red squiggly lines under dimensions.height and dimensions.width

The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

I'm trying to eradicate red squiggly, but I'm stumped as to why the typescript compiler is giving me an error. As far as I can tell, width and height are of type Number.

5

5 Answers

123
votes

Here is another example of this error occurring that might help people.

If you're using typescript and trying to compute the difference between dates (In my case I was attempting to use ISO string from database):

new Date("2020-03-15T00:47:38.813Z") - new Date("2020-03-15T00:47:24.676Z")

TypeScript Playground

It will show the error. enter image description here

However, this same exact code works if you put it in the browser console or other node environment

new Date("2020-03-15T00:47:38.813Z") - new Date("2020-03-15T00:47:24.676Z")
14137

I may be wrong, but I believe this works due to the - operator implicitly using valueOf on each of it's operands. Since valueOf on Date returns a number the operation works.

However, typescript doesn't like it. Maybe there is a compiler option for this is forcing this constrain and I'm not aware.

new Date().valueOf()
1584233296463

You can fix by explicitly making the operands number (bigint) types so the - works.

Fixed Example

new Date("2020-03-15T00:47:38.813Z").valueOf() - new Date("2020-03-15T00:47:24.676Z").valueOf()

TypeScript Playground

2
votes

you can cast the expression to number.

function findArea(dimensions: Dimensions): Number {    
    return Number(dimensions.height) * Number(dimensions.width);
}
2
votes

cleanest way I found:

const diff = +new Date("2020-03-15") - +new Date("2020-03-15")

https://github.com/microsoft/TypeScript/issues/5710

1
votes

ERROR in src/app/demo.component.ts(...): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

package.json -

"dependencies": {
    "@angular/core": "^6.1.10"
}

"devDependencies": {
    "typescript": "^2.9.2"
}

Code -

dateISOString(d: any): string {
    var nDate = new Date(d);
    var tzoffset = nDate.getTimezoneOffset() * 60000;
    var localISOTime = (new Date(nDate - tzoffset)).toISOString(); // This line gives error
    return localISOTime;
}

Solution - Add valueOf() with date

var localISOTime = (new Date(nDate.valueOf() - tzoffset.valueOf())).toISOString();