babel-plugin-transform-typescript-metadata icon indicating copy to clipboard operation
babel-plugin-transform-typescript-metadata copied to clipboard

ReferenceError occurs when referencing a class before it's defined

Open RobbieGM opened this issue 5 years ago • 3 comments

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.

RobbieGM avatar Jun 07 '20 02:06 RobbieGM

Ah, damned TDZ. Should dig into this, a try catch seems hard since we should wrap everything within a function. Maybe an helper.

leonardfactory avatar Jun 26 '20 19:06 leonardfactory

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.

obedm503 avatar Jul 27 '20 00:07 obedm503

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.

RobbieGM avatar Jul 27 '20 03:07 RobbieGM