Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - Building a class registry: Cannot use 'new' with an expression whose type lacks a call or construct signature

I have this setup:

//./things/Base.ts
export default class Base{
  constructor(){
    console.log("HI I AM A BASE THING");
  }
}

//things.ts
import Base = require('./things/Base');

export = {
  defaultThing: Base
};

//entry.ts
import Things = require('./things');

new Things.defaultThing();

What I'm trying to do is build a dictionary with the keys I want for classes of a given type, letting me change the underlying implementation without touching the consuming code. This fails with the following message

λ tsc entry.ts
entry.ts(3,1): error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

Why is this and what's the proper idiom?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

import Base = require(...) does not mix well with export default class Base.

If you add console.dir(Base) to things.ts, you will see that Base is actually a module there, not a class:

{ __esModule: true, default: [Function: Base] }

If you change that import in things.ts to

import Base from './things/Base';

then your example starts working.

The explanation is given in the typescript language specification:

An import require declaration of the form

    import m = require("mod");

is equivalent to the ECMAScript 2015 import declaration

    import * as m from "mod";

That es6 form always imports m as a module, even if it contains default export.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...