babel-plugin-transform-typescript-metadata
babel-plugin-transform-typescript-metadata copied to clipboard
ReferenceError occurs when referencing a class before it's defined
Hi Leonardo,
You mentioned in this stackoverflow discussion that you attempt prevent causing ReferenceErrors by using the typeof operator, but I showed how they can occur anyway and you said "let me check because this seems like a bug". After much head-scratching, I figured out why this is the case.
let x = 8;
console.log(typeof x); // "number"
console.log(typeof y); // "undefined"
console.log(typeof z); // ReferenceError: cannot access variable z before initialization
let z = 9;
If you don't define something at all, the typeof operator will give you "undefined". But in my case the class was defined too late, and that for some reason causes a ReferenceError. I don't know what to use instead of typeof (maybe a try-catch?) but I just wanted to let you know about this weird language kludge and how you could improve your plugin.
Ah, damned TDZ. Should dig into this, a try catch seems hard since we should wrap everything within a function. Maybe an helper.
a really simple, and maybe naive, solution is to change the declaration type from let to var. var is not constrained to the TDZ semantics.
Definitely not best to change all lets and consts to vars from the plugin as that may change behavior unexpectedly. Also in my case I used classes and they were transformed to use the let syntax.