Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one.
The issue arises when the Angular compiler (which I suspect is actually tsc behavior) transpiles all code to the targeted ES version (in this case es6), causing the check for optional chaining support to break during runtime:
export function isOpChainingSupported(): boolean {
const opChainingChecker = {
support: true
};
try {
// CODE BEFORE TRANSPILING:
// return opChainingChecker?.support;
//
// TURNS INTO
return
opChainingChecker === null || opChainingChecker === void 0 ?
void 0 :
opChainingChecker.support;
} catch {
return false;
}
}
I attempted to move this code to a separate function in a plain JavaScript file and used the 'allowJs' TS config to import it without errors...unfortunately, tsc still transpiled it.
At this point, I see three options, none of which are ideal:
- Using eval('constObj?.prop'), which poses security risks based on various sources I've consulted;
- Loading my plain JavaScript file dynamically as an asset;
- Creating an ES utility library specifically for this function (currently leaning towards this option, although it may be overkill for my situation).
My question is: Is there a simpler solution that I may have overlooked? Any input or alternative approach would be greatly appreciated!
Apologies in advance if this question seems trivial, but sometimes seeking fresh perspectives can lead to unexpected solutions!
Cheers!