Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  166] [ 1]  / answers: 1 / hits: 16196  / 4 Years ago, fri, july 31, 2020, 12:00:00

I want to import js class into ts.
But I got error This expression is not constructable.

and typescript compiler says that A does not have constructor signature.

how can I solve this?


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 in the aaa module.


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

index.d.ts in the aaa module.


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

name:string;
}

and I can construct A in js with code below. but can't in ts.


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

More From » typescript

 Answers
15

see comment below. (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.

[#50750] Monday, July 20, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alejandro

Total Points: 231
Total Questions: 102
Total Answers: 107

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
alejandro questions
Mon, Jul 18, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Thu, Sep 10, 20, 00:00, 4 Years ago
;