元素隐式具有“任何”类型,因为索引表达式不是“数字”类型 \[7015\]

新手上路,请多包涵

我从 David Walsh 的 css 动画回调中获取了代码并将其修改为 TypeScript。但是,我收到一个错误,我不知道为什么:

 interface IBrowserPrefix {
  [key: string]: string;
}

// http://davidwalsh.name/css-animation-callback
function whichAnimationEvent() {
  let x: keyof IBrowserPrefix;
  const el = document.createElement('temp');
  const browserPrefix: IBrowserPrefix = {
    animation: 'animationend',
    OAnimation: 'oAnimationEnd',
    MozAnimation: 'animationend',
    WebkitAnimation: 'webkitAnimationEnd',
  };

  for (x in browserPrefix) {
    if (el.style[x] !== undefined) {
    //           ^---- [TS Error]: Element has 'any' type b/c index expression is not of type 'number'
      return browserPrefix[x];
    }
  }
}

原文由 skube 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 595
2 个回答

发生这种情况是因为您试图使用带有字符串键的数字索引签名来索引对象。

for x in browserPrefix 会给你一组键,它们是字符串。但是由于某种原因 CSSStyleDeclaration 将其索引类型设置为 number (而不是 string )- 请参阅 https: //Microsoft.comType/issues/microsoft.comType /17827

您收到此错误是因为您打开了 --noImplicitAny 。一种使它工作的方法(一种 hacky 方法)是将索引器转换为字符串:

   for (x in browserPrefix) {
    if (el.style[x as any] !== undefined) {
      return browserPrefix[x];
    }
  }

另一种方法是修改类型(尝试在 github 上解决问题)。

当我们在这里时,你应该标记 xconst 并且如果你打算在一个对象上使用 for-in 你应该确保该属性属于对象避免引入原型链中继承的任何东西:

   for (const x in browserPrefix) {
    if (browserPrefix.hasOwnProperty(x) && el.style[x as any] !== undefined) {
      return browserPrefix[x];
    }
  }

或者,使用 for-ofObject.keys 而不是 for-in

这里不需要提前定义 x

原文由 Dan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题