【问题标题】:How can I solve error "This Expression is not constructable"?如何解决错误“此表达式不可构造”?
【发布时间】:2020-11-21 03:57:06
【问题描述】:

我想将js类导入ts。 但我收到错误 This expression is not constructable.
并且打字稿编译器说 A 没有构造函数签名。
我该如何解决?

index.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();

【问题讨论】:

    标签: javascript typescript class import


    【解决方案1】:

    请参阅下面的评论。 (original)

    // 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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多