gpt4 book ai didi

javascript - 元素隐式具有 'any' 类型,因为索引表达式不是 'number' 类型 [7015]

转载 作者:数据小太阳 更新时间:2023-10-29 04:41:30 70 4
gpt4 key购买 nike

我已经从 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-ofObject.keys 而不是 for-in

这里不需要提前定义x

关于javascript - 元素隐式具有 'any' 类型,因为索引表达式不是 'number' 类型 [7015],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526178/

70 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com