[英]Argument of type 'string | number | string[]' is not assignable to parameter of type 'string'
I have code in my typescript file 我的打字稿文件中有代码
Here is code 这是代码
slide(event, ui) {
$(`#stops_${i}`).val(`Max ${ui.value} ${__('byten')}`);
$(`#filter_stops_${i}`).val(ui.value);
if ((ui.value > 0) && ($('#filter_direct').val() === '1')) {
$('#filter_direct').parent().children('.Switch').removeClass('On').addClass('Off');
$('#filter_direct').val('0');
}
let stop_sum = 0;
$('.filter_stops').each(function() {
return stop_sum += parseInt($(`#filter_stops_${$(this).attr('id').split('_')[1]}`).val());
});
if ((stop_sum === 0) && ($('#filter_direct').val() === '0')) {
$('#filter_direct').parent().children('.Switch').removeClass('Off').addClass('On');
return $('#filter_direct').val('1');
}
}
But at this row: 但是在这一行:
return stop_sum += parseInt($(`#filter_stops_${$(this).attr('id').split('_')[1]}`).val());
when I try to do split I have this error. 当我尝试拆分时,出现此错误。
[ts] Argument of type 'string |
[ts]类型'string |的参数 number |
编号 string[]' is not assignable to parameter of type 'string'.
string []'不可分配给'string'类型的参数。 Type 'number' is not assignable to type 'string'.
不能将“数字”类型分配给“字符串”类型。
How I can fix it? 我该如何解决?
val
can return one of several types depending on the underling type of the html element. val
可以返回几种类型之一,具体取决于html元素的基础类型。 The simplest solution if you are sure this will always be a string
is to use a type assertion to string
如果您确定这将始终是
string
那么最简单的解决方案是使用类型断言来string
return stop_sum += parseInt($(`#filter_stops_${$(this).attr('id').split('_')[1]}`).val() as string);
Another option is to use type guards to distinguish between cases: 另一种选择是使用类型保护来区分大小写:
let value = $(`#filter_stops_${$(this).attr('id').split('_')[1]}`).val();
if (typeof value === "string") {
return stop_sum += parseInt(value);
}
if (typeof value === "number") {
return stop_sum += value;
} else {
throw Error("Unsupported value type")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.