我从 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 许可协议
发生这种情况是因为您试图使用带有字符串键的数字索引签名来索引对象。
for x in browserPrefix
会给你一组键,它们是字符串。但是由于某种原因CSSStyleDeclaration
将其索引类型设置为number
(而不是string
)- 请参阅 https: //Microsoft.comType/issues/microsoft.comType /17827 。您收到此错误是因为您打开了
--noImplicitAny
。一种使它工作的方法(一种 hacky 方法)是将索引器转换为字符串:另一种方法是修改类型(尝试在 github 上解决问题)。
当我们在这里时,你应该标记
x
和const
并且如果你打算在一个对象上使用 for-in 你应该确保该属性属于对象避免引入原型链中继承的任何东西:或者,使用
for-of
和Object.keys
而不是for-in
。这里不需要提前定义
x
。