作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我已经从 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];
}
}
}
最佳答案
发生这种情况是因为您正在尝试使用带有字符串键的数字索引签名来索引对象。
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];
}
}
另一种方法是修改类型(尝试在 github 上提交问题)。
当我们在这里时,你应该用 const
标记 x
并且如果你打算在一个对象上使用 for-in 你应该确保属性属于对象以避免拉入原型(prototype)链中继承的任何东西:
for (const x in browserPrefix) {
if (browserPrefix.hasOwnProperty(x) && el.style[x as any] !== undefined) {
return browserPrefix[x];
}
}
或者,使用 for-of
和 Object.keys
而不是 for-in
。
这里不需要提前定义x
。
关于javascript - 元素隐式具有 'any' 类型,因为索引表达式不是 'number' 类型 [7015],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526178/
我是一名优秀的程序员,十分优秀!