typescript 算术运算的左侧必须是“any”、“number”或枚举类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36560806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type
提问by jrahhali
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
第 7 行,下方的红色波浪线dimensions.height
和dimensions.width
The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
算术运算的左侧必须是“any”、“number”或枚举类型。
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.
我正在尝试消除红色波浪线,但我不明白为什么打字稿编译器给我一个错误。据我所知,宽度和高度是数字类型。
回答by BrunoLM
Number
should be lowercase: number
.
Number
应该是小写:number
。
回答by Matt Mazzola
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):
如果您正在使用打字稿并尝试计算日期之间的差异(在我的情况下,我试图使用数据库中的 ISO 字符串):
new Date("2020-03-15T00:47:38.813Z") - new Date("2020-03-15T00:47:24.676Z")
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.
我可能是错的,但我相信这是由于-
运算符隐式使用valueOf
它的每个操作数。由于valueOf
日期返回一个number
操作有效。
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.
您可以通过显式地使操作数编号 (bigint) 类型进行修复,以便-
工作。
Fixed Example
固定示例
new Date("2020-03-15T00:47:38.813Z").valueOf() - new Date("2020-03-15T00:47:24.676Z").valueOf()