Reputation:
I'm currently learning TypeScript but I don't know how to solve this problem properly. I want to style a HTMLElement given as a argument to my styling function like this:
function styleElement(unstyled: HTMLElement) {
const styled = unstyled.cloneNode(); // styleElement should be a pure function
styled.style = { opacity: 0 }; // TypeScript says: Property 'style' does not exist on type 'Node'.
return styled;
}
I have checked the "Node" interface declaration and the style property is missing. As far as I know it is described in the W3C spec, that Node hasn't any style property. But how can I solve my problem with this limitation?
However overwriting the style property on a "HTMLElement" triggers a readonly error, which is strange too.
Thank you!
Upvotes: 3
Views: 2039
Reputation: 174967
You can cast:
function styleElement(unstyled: HTMLElement) {
const styled = unstyled.cloneNode() as HTMLElement;
styled.style.opacity = 0 // Now works properly.
// You can't reassign HTMLElement#style, that won't work.
return styled;
}
Upvotes: 3