Here is the code snippet:
export default class App {
el: HTMLElement;
constructor(el: string | HTMLElement) {
if (typeof el === "string") {
this.el = document.getElementById(el);
}
if (typeof el === typeof this.el) {
this.el = el;
}
}
}
If you encounter a compile error message that reads:
Type 'string | HTMLElement' is not assignable to type 'HTMLElement'.
Type 'string' is not assignable to type 'HTMLElement'.ts(2322)
You can resolve it by updating the code as follows:
export default class App {
el: HTMLElement;
constructor(el: string | HTMLElement) {
if (typeof el === "string") {
this.el = document.getElementById(el);
}
if (el instanceof HTMLElement) {
this.el = el;
}
}
}
If you're wondering why one version gets an error while the other doesn't, the confusion remains.