I created a function for setting multiple HTML attributes at once -
function attrs(element: HTMLElement, attrs: { [key: string]: string | number }): void {
for (let attr in attrs) {
element.setAttribute(attr, typeof attr === 'number' ? attrs[attr].toString() : attrs[attr])
}
}
I was trying to generic object which accepts key of type string and value of type string or number. But as we know setAttribute() takes 2 args of type string. I put a check; to check whether the value is type of string or number and if the type is number I changed it to string as you can see in the function.
Even then I am getting
Argument of type 'string | number' is not assignable to parameter of type 'string'.
Type 'number' is not assignable to type 'string'.
P.S - Also suggest a better title for this question
CodePudding user response:
Use an intermediate variable to help with the narrowing:
function attrs(element: HTMLElement, attrs: { [key: string]: string | number }): void {
for (let attr in attrs) {
const attrValue = attrs[attr];
element.setAttribute(attr, typeof attrValue === 'number' ? attrValue.toString() : attrValue)
}
}
