javascript - 如何解决错误“此表达式不可构造”?
问题描述
我想将 js 类导入 ts。但我收到错误This expression is not constructable.
,打字稿编译器说 A 没有构造函数签名。
我该如何解决这个问题?
索引.ts
import A from "aaa";
const a = new A(); //error: this expression is not constructable.
/*
and result of console.log(A); is [Function: A].
result of console.log(A.toString()); is below
class A {
constructor(name) { this.name = name; }
}
*/
aaa 模块中的 index.js。
class A {
constructor(name) { this.name = name; }
}
module.exports = A;
aaa 模块中的 index.d.ts。
export declare class A {
constructor(name:string);
name:string;
}
我可以用下面的代码在js中构造A。但不能在ts。
const A = require("aaa");
const a = new A();
解决方案
请参阅下面的评论。(原创)
// Note that ES6 modules cannot directly export class objects.
// This file should be imported using the CommonJS-style:
// import x = require('[~THE MODULE~]');
//
// Alternatively, if --allowSyntheticDefaultImports or
// --esModuleInterop is turned on, this file can also be
// imported as a default import:
// import x from '[~THE MODULE~]';
//
// Refer to the TypeScript documentation at
// https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require
// to understand common workarounds for this limitation of ES6 modules.
推荐阅读
- php - 如何解决“未调度预期的 [App\Events\UserRegistered] 事件。” 错误?
- scala - 有没有办法用每行的自定义连接来连接两个 Spark 数据帧
- python - 如何展开螺旋图?
- scala - 如何在 MacOS 上的 intellij IDEA 中更改运行时 JAVA 堆空间?
- javascript - 无法以 html 形式编写 AJAX 输出变量
- c - 从浮点数中分离数字
- php - 集合无法转换为 int Laravel
- django - 如何根据品牌对产品进行分组并在 django 中获取最低价格产品
- kubernetes - Kubernetes 上的 flink 将外部 jar 加载到集群
- regex - 分析器中的自定义字符过滤器不起作用