构建类注册表:不能对类型缺少调用或构造签名的表达式使用“new" [英] Building a class registry: Cannot use 'new' with an expression whose type lacks a call or construct signature

查看:38
本文介绍了构建类注册表:不能对类型缺少调用或构造签名的表达式使用“new"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个设置:

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

推荐答案

import Base = require(...)export default class Base 不能很好地混合.

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

如果将 console.dir(Base) 添加到 things.ts,您会看到 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] }

如果您将 things.ts 中的导入更改为

If you change that import in things.ts to

import Base from './things/Base';

然后您的示例开始工作.

then your example starts working.

中给出了解释打字稿语言规范:

导入需要声明表单

    import m = require("mod");

相当于 ECMAScript 2015 的导入声明

is equivalent to the ECMAScript 2015 import declaration

    import * as m from "mod";

那个 es6 表单总是将 m 作为模块导入,即使它包含默认导出.

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

这篇关于构建类注册表:不能对类型缺少调用或构造签名的表达式使用“new"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆