How to resolve the TypeScript error of“Property ‘foo’ does not exist on type ‘HTMLElement’.”
What happened?
I’ve coded like this with TypeScript.
const blob = new Blob([response.data], { type: "application/zip" });
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "files.zip";
document.body.appendChild(a);
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
This is a program that a user can upload a CSV file, convert it to JSON, and download it as a zip file. But please only look at this part.
const a = document.createElement("a");
document.body.appendChild(a);
This code is making the DOM element of `<a>` and adding it to `<body>.` The program like this is not unique but unusual, right?
But I got the TypeScript error.
Property 'appendChild' does not exist on type 'HTMLElement'.
The error said “ `appendChild` tried to access to an object of HTMLElement, `document.body`, but`document.body` doesn't have such a property or a method”.
But we know `appendChild` is a very common method in HTMLElement, hmm….
How did I resolve it?
As a summary, I just used append
instead of appendChild
.
document.body.appendChild(a); //NG
document.body.append(a); //OK
You may know append
is common in jQuery, but it is now common in Vanilla JavaScript too.
MDN says their differences are as follows.
append
can also accept a string, butappendChild
can only do a Node object.append
doesn’t have a return value, butappendChild
can return an added Node object.append
can accept multiple Node objects and strings, butappendChild
can accept only ONE Node object.
https://developer.mozilla.org/docs/Web/API/Node/appendChild
Totally append
looks more powerful than appendChild
. (But I don’t know what the error happened this time because my code surely takes only one Node object as an argument…)
BTW, I asked ChatGPT before reaching this solution, but all of its advice didn’t work.
- Cast by `any` or `HTMLElement`
- Add `if(document?body){ … }`
- Re-install `node_modules`
- Change the settings of `tsconfig.json`
- Reboot your IDE