【发布时间】:2023-02-24 11:49:38
【问题描述】:
我在此函数的最后一行遇到以下错误:“无法分配给‘ATTRIBUTE_NODE’,因为它是只读属性。”
我尝试使用 Object.getOwnPropertyDescriptor 方法来利用保护子句,但 TypeScript 仍然无法确定我是否始终访问 readOnly 属性。大多数时候我需要访问“innerText”属性,但有时我也需要访问“src”属性来动态获取图像,这就是我使用索引方法的原因。这是一种不好的做法还是有解决办法?
function fillData(selector: string, property: string, data: string, parentElem: HTMLElement){
const targetElem = parentElem.querySelector(`[data-${selector}]`) as HTMLElement
if (!property) return
targetElem[property as keyof typeof targetElem] = data
}
【问题讨论】:
-
作为 keyof typeof targetElem 删除
-
@TachibanaShin 然后它将不再编译。
-
@TachibanaShin 刚刚重定向到一个新错误“元素隐式具有‘任何’类型,因为‘字符串’类型的表达式不能用于索引‘HTMLElement’类型。没有找到带有‘字符串’类型参数的索引签名在类型 'HTMLElement' 上。”
-
使用像this这样的受限通用参数是否满足您的需求?如果是这样,我可以把它写下来作为答案。如果没有,我错过了什么?
-
@jsejcksn 欢迎您尝试。
标签: html typescript