Búsqueda de sitios web

javascript - ¿Cómo puedo solucionar el error "Esta expresión no se puede construir"?


Quiero importar una clase js en ts. Pero obtuve el error Esta expresión no es construible.
y el compilador de TypeScript dice que A no tiene firma de constructor.
¿cómo puedo resolver esto?

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; }
}
*/

index.js en el módulo aaa.

class A {
  constructor(name) { this.name = name; }
}
module.exports = A;

index.d.ts en el módulo aaa.

export declare class A {
  constructor(name:string);

  name:string;
} 

y puedo construir A en js con el código a continuación. pero no puedo en ts.

const A = require("aaa");
const a = new A();

Respuesta #1

ver comentario abajo. (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.

Artículos relacionados