想动态的获取并修改 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.
......
这个如何处理呢?
通过
强制转换类型后报错:
是因为不知道 audio[property] 中的 property 会是哪个属性,property 可能是某个 readonly 属性,不能给该属性赋值。
我的解决办法是根据自己的业务逻辑限制 property 的范围:
这样就不报错了