Typescript: `HTMLElement.style` wrongly defined as `readonly`

Created on 15 Oct 2017  路  4Comments  路  Source: microsoft/TypeScript

The style property of HTMLElement must not be readonly. Please, read https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style#Setting_styles carefully in order to understand why.

Needs More Info

Most helpful comment

I think you've misunderstood how readonly works. It simply means that the property itself is read-only and you can't assign directly to it. But you can of course read the style property and then assign to any of its properties. In other words, this works fine:

const e: HTMLElement = getSomeHTMLElement();
e.style.backgroundColor = 'red';  // Ok

All 4 comments

Quoting from the link above: "Styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;"), since it is considered read-only"

What am I missing?

From the text you quoted, you are missing the "string" part. And if you just continue reading...

Instead, styles can be set by assigning values to the properties of style. For adding specific styles to an element without altering other style values, it is preferred to use the individual properties of style (as in elt.style.color = '...')

To me it seems that MDN's page needs some revision, but putting that aside, who hasn't at some point modified the style of an element directly? Haven't you ever done something like document.querySelector('#important-link').style.backgroundColor = 'red'?

I think you've misunderstood how readonly works. It simply means that the property itself is read-only and you can't assign directly to it. But you can of course read the style property and then assign to any of its properties. In other words, this works fine:

const e: HTMLElement = getSomeHTMLElement();
e.style.backgroundColor = 'red';  // Ok

You're absolutely right. In any case, let me briefly explain what I was trying to do. It was something like this:

function f(e: Partial<HTMLElement>) { }

f({
    style: {color: 'red'}
})

Which I wrongly thought didn't work because of the readonly. What I really needed was a recursive version of Partial, which I created like so:

type DeepPartial<T> = {
    [P in keyof T]?: DeepPartial<T[P]>
}

Thanks for your time and patience 馃槈

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jbondc picture jbondc  路  3Comments

wmaurer picture wmaurer  路  3Comments

dlaberge picture dlaberge  路  3Comments

uber5001 picture uber5001  路  3Comments

manekinekko picture manekinekko  路  3Comments