Home > Net >  How to allow multiple values for a key in typescript?
How to allow multiple values for a key in typescript?

Time:07-24

How can I declare multiple options for the value of the key of an object using typescript? I'm getting "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol'" but it does work with a single value (and suggesting it in the editor).

const addCSS = (ele: HTMLElement, obj: { [`color`]: string | number }) => {    // working
    Object.entries(obj).forEach((prop) =>
        ele.style[prop[0]] = prop[1]
    );
};
const addCSS = (ele: HTMLElement, obj: { [`color` | `background`]: string | number }) => {    // error
    Object.entries(obj).forEach((prop) =>
        ele.style[prop[0]] = prop[1]
    );
};

Thanks!

CodePudding user response:

What about using a union of interfaces?

obj: ({color: string | number} | {background: string | number})
  • Related