报错:'string' can't be used to index type 'HTMLAudioElement' 如何处理?

想动态的获取并修改 audio 的属性,

// let audio: HTMLAudioElement;
let property: string = fn(); // 获取 string 类型的属性名称
audio[property] = xxxxxx; // 赋值逻辑

vscode 报错:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'HTMLAudioElement'.
  No index signature with a parameter of type 'string' was found on type 'HTMLAudioElement'.

修改为:

audio[property as keyof HTMLAudioElement] = xxxxx; // 赋值逻辑

vscode 报错:

Cannot assign to 'CDATA_SECTION_NODE' because it is a read-only property.
Cannot assign to '一堆属性' because it is a read-only property.
......

这个如何处理呢?

阅读 2.4k
3 个回答

通过

property as keyof HTMLAudioElement

强制转换类型后报错:

Cannot assign to '一堆属性' because it is a read-only property.

是因为不知道 audio[property] 中的 property 会是哪个属性,property 可能是某个 readonly 属性,不能给该属性赋值。

我的解决办法是根据自己的业务逻辑限制 property 的范围:

let property: 'currentTime' | 'volume' | 'playbackRate';

这样就不报错了

你得理清楚逻辑,缺少类型的是 audio,所以你得想办法让 IDE 认出来它。

(audio as HTMLAudioElement)[property] = xxx;

当然也可能你赋值的属性不是标准属性,或者你的 fn() 缺少返回类型,那么你就应该去做对应的修复。或者使用 audio.setAttribute('key', value) 来修改属性。

function isAudioProperty(property: string): property is keyof HTMLAudioElement {
  const audio = new Audio();
  return property in audio;
}

let property: string = fn(); 

if (isAudioProperty(property)) {
  audio[property] = xxxxxx; // 赋值
} else {
  console.error('Invalid property name:', property);
}
推荐问题
logo
Microsoft
子站问答
访问
宣传栏