【问题标题】:How write declaration for class and namespace with same name in Typescript如何在 Typescript 中为具有相同名称的类和命名空间编写声明
【发布时间】:2017-08-17 09:10:13
【问题描述】:

我正在使用这种格式的第 3 方 Javascript 库:

var MyClass = function (name) {
    this.name = name;
}

MyClass.prototype.greet = function () {
    window.alert('Hello ' + this.name)
}

我想为此编写一个 Typescript 声明。我有这样的事情:

declare class MyClass {
    constructor(name: string);
    greet(): void;
}

这一切都很好编译,当我只想引用它按预期工作的类型时。但是我在尝试使用类实现时遇到了问题。

以这种方式使用它,它可以编译并运行,但我没有得到编译时间检查

const MyClass = (require('./MyClass') as any).MyClass;
const a = new MyClass('Bob'); //a is any

这样使用会出现编译错误

const MyClass = (require('./MyClass') as any).MyClass as MyClass;
const a = new MyClass('Bob'); //Cannot use 'new' with an expression whose type lacks a call or construct signature.

这样使用会出现编译错误

import './MyClass';
const a = new MyClass('Bob');
//duplicate identifier in MyClass.d.ts

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我会尝试这样的事情

    declare class MyClass {
        greet(): void;
    }
    
    declare type MyClassFactory = (x: string) => MyClass
    
    const factory = (require('./MyClass') as any).MyClass as MyClassFactory;
    const a = factory('Bob');
    

    也就是分离类及其构造函数

    【讨论】:

    • 谢谢你 - 我修改了这个给declare type MyClassFactory = new (x: string) => MyClass和const a = new factory('Bob');
    【解决方案2】:

    所以第一个问题是您的声明文件是针对 MyClass 模块并定义了类但没有描述模块导出的。 第二个问题是您需要在主模块中匹配导入语句。 import './MyClass' 仅用于导入副作用(见the typescript modules doc。

    根据有效的代码,看起来 MyClass 模块导出了一个具有 MyClass 属性(设置为 MyClass 类)的对象,所以这就是我添加到您的声明文件中的内容。

    js 模块的MyClass.d.ts 声明文件:

    declare class MyClass {
      constructor(name: string);
      greet(): void;
    }
    
    export { MyClass }
    

    然后在你的main.ts:

    import { MyClass } from './MyClass';
    
    let a = new MyClass('foo');
    a.greet();
    

    【讨论】:

    • 当我使用 TS 代码库迁移到 webpack 时,这对我很有帮助 - 在任何地方添加 export。
    猜你喜欢
    • 2012-02-27
    • 1970-01-01
    • 2016-01-04
    • 2013-06-05
    • 2019-12-17
    • 1970-01-01
    • 2015-11-11
    • 2018-07-24
    • 1970-01-01
    相关资源
    最近更新 更多