Why Does This Typescript Output “[Class] is not a constructor.”?

后端 未结 12 1259
清歌不尽
清歌不尽 2021-01-17 07:55

I\'m working in typescript 1.5 in visual studio. I have a main class called app.ts, and another called FizzBuzzManager.ts. I can\'t figure out what is wrong with this code,

相关标签:
12条回答
  • 2021-01-17 08:42

    This error message means that [Class] is not initialized by the time a call to its constructor is made.

    Unlike functions, classes are not “hoisted” to the top of the scope they are declared in. Whenever code uses a class that is declared later (i.e. down below in the file), this error appears.

    Solution: reorganize your code so that call sites for a class appear below that class' definition in the source code.

    0 讨论(0)
  • 2021-01-17 08:42

    I had this error my_imported_module_1.MyModule is not a constructor.

    I was using the approach when I got this error: import { MyModule } from 'my-module-sdk';

    but I got it to work when I changed it to this approach: const MyModule = require('my-module-sdk');

    In my tsconfig.json, I have "target" set to "es5", and tried changing it "es6" and that still didn't help.

    Here are some of my other tsconfig options:

    "target": "es5",
    "module": "esnext",
    "declaration": true,
    "rootDir": "./src",
    "moduleResolution": "node",
    "lib": ["es6", "dom", "es2016", "es2017", "es2018", "es2019", 
    "es2020"],
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "allowJs": false
    
    0 讨论(0)
  • 2021-01-17 08:46

    I tried to repeat your problem and I did not find any error:

    app.ts

    namespace jim {
        class Greeter {
            element: HTMLElement;
            span: HTMLElement;
            timerToken: number;
    
            constructor() {
                window.console.log("constructing Greeter.");
                this.init();
            }
    
            private init() {
                window.console.log("Calling init.");
                var _fizzBuzzManager: any = new jim.FizzBuzzManager();
            }
    
        }
    
        window.onload = () => {
            window.console.log("Hello")
            var greeter = new Greeter();
    
        };
    }
    

    FizzBuzzManager.ts

    namespace jim {
    
    export class FizzBuzzManager {
    
        constructor() {
            window.console.log("Making a FizzBuzzManager.");
        }
    
        public myThing: String = "Hi";
    
        public fizzBuzz2() {
            window.console.log("fizzbuzzing2 " + this.myThing);
        }
    
    }
    
    export function fizzBuzz() {
        window.console.log("export function fizzbuzz");
    }
    
    }
    

    Then

    c:\Work\TypeScript-playground>node_modules\.bin\tsc --out app.js app.ts FizzBuzzManager.ts
    

    and compiled app.js file looks like this:

    var jim;
    (function (jim) {
        var Greeter = (function () {
            function Greeter() {
                window.console.log("constructing Greeter.");
                this.init();
            }
            Greeter.prototype.init = function () {
                window.console.log("Calling init.");
                var _fizzBuzzManager = new jim.FizzBuzzManager();
            };
            return Greeter;
        })();
        window.onload = function () {
            window.console.log("Hello");
            var greeter = new Greeter();
        };
    })(jim || (jim = {}));
    var jim;
    (function (jim) {
        var FizzBuzzManager = (function () {
            function FizzBuzzManager() {
                this.myThing = "Hi";
                window.console.log("Making a FizzBuzzManager.");
            }
            FizzBuzzManager.prototype.fizzBuzz2 = function () {
                window.console.log("fizzbuzzing2 " + this.myThing);
            };
            return FizzBuzzManager;
        })();
        jim.FizzBuzzManager = FizzBuzzManager;
        function fizzBuzz() {
            window.console.log("export function fizzbuzz");
        }
        jim.fizzBuzz = fizzBuzz;
    })(jim || (jim = {}));
    

    Chrome browser reports in its console:

    app.js:15 Hello
    app.js:5 constructing Greeter.
    app.js:9 Calling init.
    app.js:24 Making a FizzBuzzManager.
    

    There is a good explanation of the error you are getting here: Javascript: TypeError: ... is not a constructor (not that it reveals the origin of the problem but you may see the problem in your transpiled code.)

    0 讨论(0)
  • 2021-01-17 08:46

    For future readers, the problem could also be if the constructor expects parameters and you are giving no parameters or a different number of parameters. This is because for Javascript a function with a different number of parameters is a different function.

    A simple solution could be to add default parameters in the constructor.

    My example was like this:

    SegmentsQueryBuilder.ts

    class SegmentsQueryBuilder {
      //...
      constructor(scoping) {
        //...
      }
    //...
    }
    

    segments.query.builder.test.ts

    describe('Segment base query', () => {
      test('should create segment select with default fields', () => {
        const segmentQueryBuilder = new SegmentQueryBuilder() //ERROR HERE
    //...
    

    The solution here was either to use default parameter in the constructor or to pass the scoping object in the usage of the constructor

    0 讨论(0)
  • 2021-01-17 08:49

    I came upon this question after googling "typescript is not a constructor". Unfortunately, these answers did not resolve my problem. I eventually found the solution, so I am posting it here for posterity.

    Problem

    I defined the following TypeScript class:

    module mymodule {
        export class myclass {
            addDocuments(parentId: string) {
            // Code removed for brevity...
            }
        }
    }
    

    I then called the class in a separate module:

    module mymodule.test {
    
        var myClass = new mymodule.myclass();
    
        export function initialize(): void {
            myClass.addDocuments("test123");
        }
    }
    

    After compiling and while attempting to load the page that executes the resulting Javascript, the page wouldn't load properly and I saw the following JS exception:

    Uncaught TypeError: mymodule.myclass is not a constructor

    Solution

    A fellow developer was kind enough to point out that I needed to move the instantiation of the object inside of my function. So now my instantiation code looks like this and it works as it should:

    module mymodule.test {
    
        var myClass: mymodule.myclass;
    
        export function initialize(): void {
            myClass = new mymodule.myclass();
            myClass.addDocuments("test123");
        }
    }
    
    0 讨论(0)
  • 2021-01-17 08:49

    Which typescript version do you use?

    There is a Bug in tsc 1.8.10:

    https://github.com/Microsoft/TypeScript/issues/8910

    0 讨论(0)
提交回复
热议问题