Borislav Hadzhiev
Sun Mar 20 2022·2 min read
Photo by Viktor Vasicsek
The error "Property 'disabled' does not exist on type 'HTMLElement'" occurs
when we try to access the disabled
property on an element that has a type of
HTMLElement
. To solve the error, use a type assertion to type the element as
HTMLButtonElement
.
This is the index.html
file for the examples in this article.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <button id="btn">Submit</button> <script src="./src/index.ts"></script> </body> </html>
And here is an example of how the error occurs in the index.ts
file.
const btn = document.getElementById('btn'); if (btn != null) { // ⛔️ Property 'disabled' does not exist on type 'HTMLElement'.ts(2339) btn.disabled = true; }
The reason we got the error is because the return type of the
document.getElementById
method is HTMLElement | null
and the
disabled
property doesn't exist on the HTMLElement
type.
To solve the error, use a type assertion to type the element as an
HTMLButtonElement
(or HTMLInputElement
, HTMLTextAreaElement
,
HTMLSelectElement
, HTMLOptionElement
- depending on what element you're
typing).
const btn = document.getElementById('btn') as HTMLButtonElement | null; if (btn != null) { btn.disabled = true; }
Type assertions are used when we have information about the type of a value that TypeScript can't know about.
btn
variable stores anHTMLButtonElement
or a null
value and not to worry about it.We used a
union type
to specify that the variable could still be null
, because if an HTML element
with the provided id
is not present in the DOM, the getElementById()
method
returns a null
value.
We used a simple if
statement that serves as a
type guard
to make sure the btn
variable doesn't store a null
value before accessing
its disabled
property.
const btn = document.getElementById('btn') as HTMLButtonElement | null; // 👉️ btn has type HTMLButtonElement or null here if (btn != null) { // 👉️ btn has type HTMLButtonElement here btn.disabled = true; }
btn
variable has a type of HTMLButtonElement
in the if
block and allows us to directly access its disabled
property.It's always a best practice to include null
in the type assertion, because the
getElementById
method would return null
if no element with the provided id
was found.
You could also use the
optional chaining (?.)
operator to get around the possibly null
value if you only have to access the
disabled
property.
const btn = document.getElementById('btn') as HTMLButtonElement | null; const disabled = btn?.disabled; console.log(disabled)
The optional chaining operator short-circuits returning undefined
if the
reference is equal to null
or undefined
.
In other words, if the btn
variable stores a null
value, we won't attempt to
call the disabled
property on null
and get a runtime error.
However, note that you cannot use the optional chaining (?.) operator on the
left hand side of an assignment. For example, you can't do
btn?.disabled = true
.