我正在开发一个普通的JavaScript库,并定义了一个JS类如下所示:
class MyClass {
static create() {
return new MyClass();
}
doOneThing() {
// ...
return this;
}
doOtherThing() {
// ...
return this;
}
}
module.exports = MyClass;所以我可以使用类似dsl的语法:
MyClass
.create()
.doOneThing()
.doOtherThing();我正在尝试为这个类添加d.ts类型文件,供其他TypeScript开发人员使用。到目前为止我能做到的最好的事:
export interface MyClassInstance {
doOneThing(): MyClassInstance;
doOtherThing(): MyClassInstance;
}
export interface MyClassStatic {
create(): MyClassInstance;
}
declare const MyClass: MyClassStatic;
export default MyClass;因此,它适用于TypeScript:
import MyClass from "./src/MyClass";但是在一个JavaScript文件中,我的IDE通过自动完成工具为我提供了以下内容:
MyClass.default.create();我想我可以添加强制性的析构,导出包装在对象中的类:
module.exports = {MyClass};然后TS和JS都以相同的方式工作。但我不想。
因此,我想知道,是否还有另一种方法--在JS和TS中同时拥有静态方法和默认的导出世界。
更新1
看来,我可以在.d.ts文件中声明类而不是接口,如下所示:
declare class MyClass {
static create(): MyClass;
doOneThing(): this;
doOtherThing(): this;
}
export default MyClass;JS和TS似乎都很好,但是我仍然在检查它是好的,还是“不”或者是不好的练习。
更新2
看来这是我能得到的最好的了。我还检查了DefinitelyTyped回购,一些模块在它们的类型中使用了class声明,所以我想没关系。
发布于 2019-02-09 11:25:37
https://stackoverflow.com/questions/54600291
复制相似问题