Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery和类型为';字符串|数字|字符串[]和#x27;不可分配给类型为';字符串';。_Jquery_Typescript_Types - Fatal编程技术网

Jquery和类型为';字符串|数字|字符串[]和#x27;不可分配给类型为';字符串';。

Jquery和类型为';字符串|数字|字符串[]和#x27;不可分配给类型为';字符串';。,jquery,typescript,types,Jquery,Typescript,Types,我有一个现有的大型项目,它正在转换为typescript,最终将被重构,然后放入Angular中。当前项目中有很多Jquery。我在项目中实现了一个当前的@types 问题是这条线 if (["Priority", "PM"].indexOf($('option:selected', this).val()) >= 0) { 由于类型定义,正在创建错误。我得到类型为“string | number | string[]”的[TS]参数不能分配给类型为“string”的参数。因为index

我有一个现有的大型项目,它正在转换为typescript,最终将被重构,然后放入Angular中。当前项目中有很多Jquery。我在项目中实现了一个当前的@types

问题是这条线

if (["Priority", "PM"].indexOf($('option:selected', this).val()) >= 0) {
由于类型定义,正在创建错误。我得到类型为“string | number | string[]”的[TS]参数不能分配给类型为“string”的参数。因为indexOf被定义为“(method)Array.indexOf(searchElement:string,fromIndex?:number):number”,而Jquery的.val被定义为“Jquery.val():string | number | string[](+1重载)”


我需要一种方法来覆盖.val定义,只覆盖字符串,这样我就可以对像这样的行进行编译,而不覆盖整个项目的.val。我在项目中有很多这样的行,所以我还不能重写其中的每一行。最终我们将完全摆脱Jquery。如果有人能给我指出正确的方向,那就太好了。

我终于想出了如何让它发挥作用。我能够将类型字符串转换为它。因为我在项目中的几个地方都有这条直线,所以我创建了一个如下的变量:

let optSel: string = <string>$('option:selected', this).val();

if ($(["Priority", "PM"]).index(optSel) >= 0) {
让optSel:string=$('option:selected',this.val();
如果($([“优先级”,“PM”])。索引(optSel)>=0){

这使我能够确保.val类型是与Array.indexOf(searchElement:string.Hope)的indexOf要求相匹配的字符串。

您当前的方法是一个有效的解决方案,但这将要求您强制转换所有出现的
$('option:selected').val()<代码> >“代码>字符串< /代码>。您可能需要考虑的是使用环境声明,其中覆盖/扩展到<代码> jQualStrase接口,在<代码> @类型/jQuery 
interface JQueryStatic {
    (opts: 'option:selected', ...args): {
        val: () => string;
    };
}
每当调用
$('option:selected',…)
时,此调用的定义将坚持返回的对象包含返回字符串值的
val
方法

let value: string = $('option:selected').val();

如果您在整个项目中在多个文件中使用它,您可以为它创建一个声明文件(*d.ts),否则我建议只在当前文件的顶部添加环境类型声明。

听起来当前最好的方法是
让optSel:string=($('option:selected',this).val()作为字符串);