【问题标题】:How to check if a property is readOnly in TypeScript?如何检查 TypeScript 中的属性是否为只读?
【发布时间】: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


【解决方案1】:

您收到的错误消息告诉您不能为只读属性赋值。在这种情况下,targetElem 元素的 ATTRIBUTE_NODE 属性很可能是只读的。

如果您需要访问 targetElem 元素的 innerText 和 src 属性,您可以在尝试设置之前添加检查以查看该属性是 innerText 还是 src。您可以通过使用 if 语句或 switch 语句分别处理每个属性来做到这一点。这是一个例子:

function fillData(selector: string, property: string, data: string, parentElem: HTMLElement){
  const targetElem = parentElem.querySelector(`[data-${selector}]`) as HTMLElement
  
  if (!property) return

  switch(property) {
    case 'innerText':
      targetElem.innerText = data
      break;
    case 'src':
      targetElem.setAttribute('src', data)
      break;
    default:
      targetElem[property as keyof typeof targetElem] = data
      break;
  }
}

此代码使用 switch 语句检查属性值并分别处理 innerText 和 src 属性。如果属性值不是这两者之一,它会使用您已经使用的动态键语法设置属性。

请注意,在设置 src 属性的情况下,我们使用 setAttribute 方法而不是直接设置属性。这是因为 src 属性在某些元素(例如 HTMLImageElement)上是只读属性,因此直接设置它可能并非在所有情况下都有效。

【讨论】:

  • 这有效但没有消除原始错误,TypeSrcipt 在涉及到默认情况时仍然不确定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 2019-08-23
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多