代码之家  ›  专栏  ›  技术社区  ›  deathangel908

ts2351:如何在ts中为“new function()”创建构造函数类型

  •  1
  • deathangel908  · 技术社区  · 7 年前

    我正在创建一个npm包,它导出默认的一个类。这个模块是用es3编写的,但是我想提供 types.ts

    索引.js (在我的包裹里)

    function MyClass(p1, p2) {
      // code
    }
    
    module.exports =  MyClass;
    

    好的,然后我创建了类型 索引文件 (在我的包中,除了index.js):

    declare module 'mypackageid' {
      interface MyClass {
        new (div: HTMLElement, conf: any): MyClass;
      }
      export var MyClass: MyClass;
    }
    

    我可以很容易地在es3中使用这段代码,并且它是有效的。(在我的包裹之外,例如从另一个包裹)

    var myInstance = new MyClass()
    

    但如果我想从.ts文件中的另一个包中使用它:

    import MyClass from 'mypackageid';
    
    new MyClass(divReference, { // <-- error points to this line
        onBlobPaste: e=> {
          console.log(e);
        },
    });
    

    typescript加载程序拒绝编译和打印:

    TS2351:不能对类型缺少调用的表达式使用“new” 或者构造签名。

    编辑1 以下内容:

    在.ts文件和.d.ts文件中使用commonjs默认导出 指定一个成员导出,而您的使用者期望ES6 默认导出。你到底想用什么方式出口?你 必须选一个

    我没有显式地导入类型,我希望typescript从'index.d.ts'自动检测类型。如果我像这样使用默认导出:

    declare module 'mypackageid' {
      interface MyClass {
        new (div: HTMLElement, conf: any): MyClass;
      }
      export default MyClass
    }
    

    我将在下面得到错误。错误指向 new

    s2693:“myClass”仅指类型,但在此处用作值。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    7 年前

    如果你使用 exports= 在模块中的方法,因此替换模块的整个导出,您将需要使用 import= ,以及支持此功能的模块系统(如amd或commonjs)。见 docs

    mypackageid.d.ts
    declare module 'mypackageid' {
        class MyClass {
            constructor(div: HTMLElement, conf: any);
        }
        export = MyClass;
    }
    
    
    //Usage
    import MyClass = require('mypackageid')
    
    new MyClass(null, null)
    

    如果要使用 new ,不能是您需要声明 const 并导出:

    declare module 'mypackageid' {
        interface MyClassCtor {
            new (div: HTMLElement, conf: any) : {};
        }
        const MyClass : MyClassCtor;
        export = MyClass;
    }
    
    推荐文章