gpt4 book ai didi

typescript - 构建类注册表 : Cannot use 'new' with an expression whose type lacks a call or construct signature

转载 作者:搜寻专家 更新时间:2023-10-30 22:03:55 25 4
gpt4 key购买 nike

我有这个设置:

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

我想做的是用我想要的给定类型的类的键构建一个字典,让我在不触及使用代码的情况下更改底层实现。失败并显示以下消息

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

这是为什么呢?正确的成语是什么?

最佳答案

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

如果你将console.dir(Base)添加到things.ts,你会看到Base实际上是那里的一个模块,而不是一个类:

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

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

import Base from './things/Base';

然后您的示例开始工作。

解释在 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";

那个 es6 形式总是将 m 作为一个模块导入,即使它包含默认导出也是如此。

关于typescript - 构建类注册表 : Cannot use 'new' with an expression whose type lacks a call or construct signature,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39578040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com