元素隐式地具有“ any”类型,因为索引表达式不是“ number”类型[7015]

sku*_*ube 7 javascript typescript

我已经从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];
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*try 7

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

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

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

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

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

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

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

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

这里不需要x提前定义。