typescript 为什么此打字稿输出“[Class] 不是构造函数。”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34581714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why Does This Typescript Output "[Class] is not a constructor."?
提问by Jim
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, but it outputs the error, "TypeError: jim.FizzBuzzManager is not a constructor".
我正在 Visual Studio 中使用 typescript 1.5。我有一个名为 app.ts 的主类,另一个名为 FizzBuzzManager.ts。我不知道这段代码有什么问题,但它输出错误,“TypeError: jim.FizzBuzzManager is not a constructor”。
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
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");
}
}
The output when looking at the compiled output in a browser is this:
在浏览器中查看编译输出时的输出是这样的:
Hello app.js:15:9
constructing Greeter. app.js:5:13
Calling init. app.js:9:13
TypeError: jim.FizzBuzzManager is not a constructor app.js:10:36
回答by basarat
TypeError: jim.FizzBuzzManager is not a constructor
类型错误:jim.FizzBuzzManager 不是构造函数
This is a common error when you use --out
: https://basarat.gitbook.io/typescript/main-1/outfile
这是使用时的常见错误--out
:https: //basarat.gitbook.io/typescript/main-1/outfile
You are responsible for loading the files in the right order. Don't use out and use external modules
您负责以正确的顺序加载文件。不要用完并使用外部模块
回答by Tod Birdsall
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:
我定义了以下 TypeScript 类:
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:
编译后并尝试加载执行结果 Javascript 的页面时,页面无法正确加载,我看到以下 JS 异常:
Uncaught TypeError: mymodule.myclass is not a constructor
未捕获的类型错误:mymodule.myclass 不是构造函数
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");
}
}
回答by Alexander Zeitler
When migrating from plain ES6 / Node.js using module.exports
/require()
it often happens to me that I forget to remove the old module.exports = <class>
which also causes this error.
当使用module.exports
/从普通 ES6 / Node.js 迁移require()
时,我经常会忘记删除旧的module.exports = <class>
,这也会导致此错误。
回答by glitchbane
It might be helpful to think about it as if you were writing the code in JavaScript directly. I came across this question because I got the same error in an Angular 2 test spec written in TypeScript. After thinking about it based on the answers above, I realized that JavaScript would have no idea what my equivalent to your BuzzFeed class was because it was at the bottom of the file.
将其视为直接用 JavaScript 编写代码可能会有所帮助。我遇到了这个问题,因为我在用 TypeScript 编写的 Angular 2 测试规范中遇到了同样的错误。在根据上述答案考虑之后,我意识到 JavaScript 不知道与您的 BuzzFeed 类等效的内容是什么,因为它位于文件的底部。
I moved the class up to the top of the file before my first describe statement and everything works. Thought this might help others like myself.
在我的第一个 describe 语句之前,我将班级移到了文件的顶部,一切正常。认为这可能会帮助像我这样的其他人。
回答by Martin Vseticka
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
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:
编译后的 app.js 文件如下所示:
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:
Chrome 浏览器在其控制台中报告:
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.)
您在这里得到的错误有一个很好的解释:Javascript: TypeError: ... is not a constructor(不是它揭示了问题的根源,但您可能会在转译的代码中看到问题。)
回答by Christian Kuetbach
Which typescript version do you use?
您使用哪个打字稿版本?
There is a Bug in tsc 1.8.10:
tsc 1.8.10 有一个 Bug:
回答by Mike Mitterer
In my case I had the problem when I used babel with preset-env to compile TS-sources.
就我而言,当我使用 babel 和 preset-env 来编译 TS-sources 时遇到了问题。
Works:
作品:
{
"presets": ["@babel/typescript"],
"plugins": [
"@babel/proposal-class-properties",
"@babel/proposal-object-rest-spread",
"@babel/plugin-transform-runtime"
],
"ignore": ["node_modules", "src/test"]
}
Wrong:
错误的:
{
"presets": [
"@babel/typescript",
[
"@babel/preset-env",
{
"targets": {
"browsers": [
"last 2 Chrome versions",
"last 1 Safari versions",
"last 1 Firefox versions"
]
}
}
]
],
"plugins": [
"@babel/proposal-class-properties",
"@babel/proposal-object-rest-spread",
"@babel/plugin-transform-runtime"
],
"env": {
"node": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"esmodules": true,
"node": "current"
},
"modules": "auto"
}
]
]
}
},
"ignore": ["node_modules", "src/test"]
}
回答by Mahdi Rastegari
at first, make sure that use
首先,请确保使用
/// <reference path = "FizzBuzzManager.ts" />
to refrence code to another .ts file at typescript root file
将代码引用到打字稿根文件中的另一个 .ts 文件
to compile typescript files that exist in different file.ts use this command
编译不同文件中存在的打字稿文件.ts 使用此命令
tsc --out app.js app.ts
tsc --out app.js app.ts
because this command converts all typescript files into app.js
因为此命令将所有打字稿文件转换为 app.js
回答by DomQ
This error message means that [Class]
is not initialized by the time a call to its constructor is made.
此错误消息意味着[Class]
在调用其构造函数时尚未初始化。
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.
解决方案:重新组织您的代码,以便类的调用站点出现在源代码中该类的定义下方。
回答by Joey Garcia
I had this error my_imported_module_1.MyModule is not a constructor
.
我有这个错误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';
当我收到此错误时,我正在使用该方法:
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');
但是当我将其更改为这种方法时,它开始工作了:
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.
在我的 tsconfig.json 中,我将“目标”设置为“es5”,并尝试将其更改为“es6”,但仍然没有帮助。
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
以下是我的一些其他 tsconfig 选项:
"target": "es5",
"module": "esnext",
"declaration": true,
"rootDir": "./src",
"moduleResolution": "node",
"lib": ["es6", "dom", "es2016", "es2017", "es2018", "es2019", "es2020"],
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"allowJs": false