One can trust the element, whether it is in the DOM or not, as it will always remain an HTMLElement.
const element = document.querySelector('div');
console.log(element instanceof HTMLElement);
element.remove();
console.log(element instanceof HTMLElement);
<div>div</div>
If attempting to perform actions that require the element to be part of the DOM when it is not attached, a warning will be issued. For instance, trying to execute:
const parent = document.querySelector('parent');
parent.appendChild(element);
would necessitate modifying it to something like:
const parent = document.querySelector('parent');
if(!parent) throw new Error('Error.');
parent.appendChild(element);
Even with various function calls and async/await statements inserted between the throwing line and accessing the element?
Indeed, this remains safe, as long as the variable retains its original assignment - ensuring it does not undergo mutation from an HTMLElement to another type guarantees safety regardless of additional code execution.
Are there instances where trusting TypeScript may not be advisable?
Exceptions exist in almost every aspect of programming. TypeScript, being human-created, contains bugs. However, given its extensive development history, numerous issues have been rectified. The remaining ones are typically uncommon in standard script writing processes.
In my experience, TypeScript challenges often center around the program requiring additional input from the developer for proper type inference through techniques like type assertions or guards. Instances where TypeScript wrongly identifies a type as A instead of B are infrequent in well-structured codebases (that avoid excessive use of 'any' types and 'as' conversions). In my significant exposure to TS, encountering such issues has been rare. Type warnings are more commonly false positives, with minimal occurrences of false negative inferences.