【问题标题】:Typescript - jQuery each index is stringTypescript - jQuery 每个索引都是字符串
【发布时间】:2018-07-30 13:28:29
【问题描述】:

出于某种原因,Typescript 在以下 jQuery 循环中将 index 报告为字符串。

$.each(locations, (index, marker) => {

    if(this.options && this.options.bounds_marker_limit) {
        if(index <= (this.options.bounds_marker_limit - 1)) this.bounds.extend(position);
    } else {
        this.bounds.extend(position);
    }
});

Typescript 正在报告

运算符“

换行

if(index &lt;= (this.options.bounds_marker_limit - 1)) this.bounds.extend(position);.

如果我尝试(index as number) 然后它会报告

类型“字符串”不能转换为类型“数字”

我可以做些什么来修复这个错误?

【问题讨论】:

  • “locations”数组包含哪些元素?

标签: jquery typescript types casting


【解决方案1】:

试试parseInt():

if(parseInt(index) <= (this.options.bounds_marker_limit - 1))

或者像这样:

locations.each((index: number, elem: Element): void => {
   // index is a number
})

根据 jQuery typescript 声明文件:

each(func: (index: number, elem: Element) => any): JQuery;

【讨论】:

  • 设置(index: number) 有效,我什至没有意识到您可以设置其他函数返回的属性类型!
猜你喜欢
  • 2011-10-20
  • 2016-12-26
  • 2023-03-19
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多