Shaun Xu
Shaun Xu

Reputation: 4656

Typescript ReferenceError: MyClass not defined, when I used MyClass inside a constructor

I have a class defined in my_class.ts

export default class MyClass {}

And I have another class using it inside the constructor

import MyClass from "./my-class.ts";
export default class MyOtherClass {
    constructor(public myClass: MyClass) {}
}

In my main.ts I got reference error when running the code (no error when compiled)

import MyClass from "./my-class.ts";
import MyOtherClass from "./my-other-class.ts";
const myOtherClass = new MyOtherClass(new MyClass());
                                          ^^^^^^^
        ReferenceError: my_class_1 is not defined

And if I changed my code to

const myClass = new MyClass();
const myOtherClass = new MyOtherClass(myClass);

It worked.

This happened when I upgrade TypeScript from 2.8.3 to 2.9.1. I checked the compiled JavaScript code and they were exactly same between 2.8.3 and 2.9.1.

Upvotes: 2

Views: 61

Answers (1)

Shaun Xu
Shaun Xu

Reputation: 4656

I figured out the root cause. This is related with some changed in TypeScript transpile module in v2.9. When I was compile and run my source code, or using ts-node with default options, everything works well. But when I was using node -r ts-node/register/transpile-only main.ts, I got this error.

Developer in TypeScript already acknowledge this issue and they said it will be fixed in v2.9.2.

https://github.com/TypeStrong/ts-node/issues/591 https://github.com/Microsoft/TypeScript/issues/24620

Upvotes: 1

Related Questions