Javascript UnhandledPromisejectionWarning:导出typescript文件时未找到函数
我在一个节点api中创建了一个ts文件,并将其导出 下面是myClass.ts文件的代码Javascript UnhandledPromisejectionWarning:导出typescript文件时未找到函数,javascript,node.js,typescript,export,es6-promise,Javascript,Node.js,Typescript,Export,Es6 Promise,我在一个节点api中创建了一个ts文件,并将其导出 下面是myClass.ts文件的代码 class myClass{ firstFunction(firstParam, secondParam) { return firstParam + secondParam }; } module.exports.myClass = myClass; 有一个js文件是index.js 下面是代码 const myClass= require('./myClass.ts
class myClass{
firstFunction(firstParam, secondParam) {
return firstParam + secondParam
};
}
module.exports.myClass = myClass;
有一个js文件是index.js
下面是代码
const myClass= require('./myClass.ts');
myFunction(){
myClass.firstFunction("firstValue", "secondValue");
}
但是使用上面的代码,我得到了下面的异常。
**UnhandledPromiseRejectionWarning: TypeError: myClass.firstFunction is not a function**
at "myMachinePath\index.js:368:20"
at processTicksAndRejections (internal/process/task_queues.js:94:5)
warning.js:27
(node:14944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
是否可以使用require在js中使用ts文件
我已尝试安装
npm install --save-dev babel-cli babel-preset-es2015
但我还是得到了同样的例外。我无法将我的js文件更改为ts
更新
如果我对myClass.ts文件进行以下更改,它工作正常。不确定这是否是正确的方法
myClass = {
firstFunction(firstParam, secondParam) {
return firstParam + secondParam
};
}
module.exports = myClass;
要么让你的方法是静态的
class myClass{
static firstFunction(firstParam, secondParam) {
return firstParam + secondParam
};
}
module.exports = myClass;
或者创建类的实例,然后调用函数
const MyClass= require('./myClass.ts');
myFunction(){
const myClass = new MyClass();
myClass.firstFunction("firstValue", "secondValue");
}
如果不创建类的对象(
myClass
),则无法调用方法。请检查以下解决问题的代码:
myClass.ts
class myClass{
constructor(){}
static firstFunction(firstParam, secondParam) {
return firstParam + secondParam
};
}
module.exports.myClass = myClass;
const myClass= require('./myClass.ts');
myFunction(){
new myClass().firstFunction("firstValue", "secondValue");
}
index.js
class myClass{
constructor(){}
static firstFunction(firstParam, secondParam) {
return firstParam + secondParam
};
}
module.exports.myClass = myClass;
const myClass= require('./myClass.ts');
myFunction(){
new myClass().firstFunction("firstValue", "secondValue");
}
您可以直接从myClass.ts文件导出对象,如下所示:
module.exports.myClass = new myClass();
因此,您不需要在index.js文件中创建对象:
const myClass= require('./myClass.ts');
myFunction(){
myClass.firstFunction("firstValue", "secondValue");
}
希望此解决方案对您有效。您ts文件中的代码似乎不是typescript。@AZ_u实际上是typescript,为什么您觉得不是?我也尝试过,下面是我未处理的例外Promisejection警告:TypeError:myClass不是构造函数这也不起作用,现在我觉得这更多的是一个配置问题,而不是代码问题。我是否需要为承诺等安装任何节点模块/库?