[英]Error While Converting JavaScript to TypeScript
I'm trying to convert some js to ts and got error in canSave method .My JavaScript code is, 我正在尝试将一些js转换为ts并在canSave方法中出错。我的JavaScript代码是,
scope.canSave = function () { if (scope.category.orderNumber != scope.list) { !_this.orderNumberAlreadyExist(scope.list, scope.category); } };
and when I'm trying to convert that into TypeScript . 当我试图将其转换为TypeScript时。 I was getting
Type '() => void' is not assignable to type '() => boolean'
and Operator '!=' cannot be applied to types 'number' and 'Category[]'
in command prompt. 我正在获取
Type '() => void' is not assignable to type '() => boolean'
并且Operator '!=' cannot be applied to types 'number' and 'Category[]'
命令提示符中的Operator '!=' cannot be applied to types 'number' and 'Category[]'
。 What was my mistake and what can i do now, can some one clarify me. 我的错误是什么,我现在该怎么办,有人可以澄清一下。
Basically, you're running into the fact that TypeScript (as the name would suggest!) has a much stricter type system than JavaScript, so a lot of things that would be allowed in the latter will cause the TypeScript compiler to shout at you. 基本上,您会遇到这样一个事实,即TypeScript(顾名思义!)具有比JavaScript更严格的类型系统,因此后者中允许的许多事情都会导致TypeScript编译器向您大喊大叫。
You have two issues here: 您在这里有两个问题:
scope.canSave
is being defined to be a function with no parameters that returns a boolean. scope.canSave
被定义为一个没有参数的函数,该函数返回布尔值。 TypeScript represents this as () => boolean
- if it took a number as a parameter, it'd look something like (number) => boolean
, and so on. () => boolean
如果将数字作为参数,则外观类似于(number) => boolean
,依此类推。 Your new function definition, on the other hand, doesn't return anything at all. () => void
- it can tell this doesn't match up to what scope.canSave
should be, so it gives you an error message. () => void
scope.canSave
它可以告诉它与范围不符scope.canSave
应该是什么,因此会给您一条错误消息。 scope.category.orderNumber
is defined as being a number, but scope.list
is defined as being an array of Category
objects. scope.category.orderNumber
定义为数字,但scope.list
定义为Category
对象的数组。 Those two types aren't comparable (you can't convert an array of objects into a number), so TypeScript gives you an error when you try to use the !=
operator on them. !=
运算符时,TypeScript会给您一个错误。 So effective, TypeScript is doing exactly what it's designed to do here - it caught two issues with your code that might have gone unnoticed in plain JavaScript. 如此有效,TypeScript完全可以按照此处设计的去做-捕获了您的代码中的两个问题,这些问题在普通JavaScript中可能并未引起注意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.