简体   繁体   中英

Generic Object that accepts only string key pair values in Typescript

How do I convert this function to Typescript?

interface Attribute {
  src?: string;
  alt?: string;
  href?: string;
  title?: string;
  target?: string;
}

function setAttributes(element: HTMLElement, attributes: Attribute){
  for (const key in attributes) {
    element.setAttribute(key, attributes[key]); // this part fails
  }
}

Here, attributes[key] fails to work. How can I work around this?

I have restructured the function like so:

function setAttributes(element: HTMLElement, attributes: Attribute) {
  for (const [key, value] of Object.entries(attributes as Record<string, string>)) {
    element.setAttribute(key, value);
  }
}

But Typescript throws an error for Object.entries saying

Property 'entries' does not exist on type 'ObjectConstructor'

Usually i just use a keyof type assertion in that case:

function setAttributes(element: HTMLElement, attributes: Attribute) {
  for (const key in attributes) {
    const value = attributes[key as keyof Attribute];

    // still might error, because value could be undefined
    element.setAttribute(key, value);
  }
}

This snippet actually works once I added "ES2017" to the tsconfig 's lib

current working snippet

function setAttributes(element: HTMLElement, attributes: Attribute) {
  for (const [key, value] of Object.entries(attributes as Record<string, string>)) {
    element.setAttribute(key, value);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM