Is there a more efficient approach to handling type checking for variables defined as type | type2? For instance, consider the following code snippet:
if (e) {
let targetElement: Element | undefined = e.toElement;
if (targetElement) {
let medicineCategory: string | null = targetElement.textContent;
if (medicineCategory) {
$('#selected-medicine-info').text(medicineCategory);
}
}
}
Having multiple checks in the code for !undefined and !null can seem cumbersome, especially when dealing with deeper nesting.
I came up with a slightly cleaner solution that allows me to easily determine if the value of textContent was null:
let targetElement: Element | undefined = e.toElement;
if (targetElement) {
let medicineCategory: string | null = (targetElement.textContent !== null) ? targetElement.textContent : "null";
$('#selected-medicine-info').text(medicineCategory);
}