仅将类型导出为打字稿定义文件中的类型

时间:2019-11-22 15:20:53

标签: typescript types typescript-typings .d.ts

假设您有一个名为my-lib的ES6库,

export class Foo {
   ...
   createBar() {
      return new Bar();
   }
   ...
}
class Bar() {
   method1() {}
   method2() {}
   method3() {}
}

,您必须像上面那样为上述库编写打字稿定义。

export class Foo() {
    ...
    public createBar():Bar;
}
export class Bar() {
   method1(): void
   method2(): void
   method3(): void
}

我的问题是:应该导出Bar类吗?

如果是,则通过编写以下代码

import { Bar } from 'my-lib'

将导致声明一个未定义的Bar变量

如果否,则以下语句将是错误的,因为未导入Bar

const foo = new Foo()
const bar: Bar = foo.createBar();

我应该如何定义Bar类,以便将其导出为类型而不是类?

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解您要实现的目标,但是如果您不想直接公开您的类,而是只公开其“形状”(类型),则可以将其定义为接口。

export class Foo {
    createBar(): IBar {
        return new Bar();
    }
}

class Bar {
    method1() { }
    method2() { return 'test'; }
    method3() { return true; }
}

export interface IBar {
    method1: () => void,
    method2: () => string,
    method3: () => boolean,
}

const foo = new Foo()
const bar: IBar = foo.createBar();

然后仅导入Foo和IBar。