简体   繁体   English

仅将 class 导出为 typescript 定义文件中的类型

[英]Exporting a class ONLY as a type in a typescript definition file

Suppose that you have an ES6 library named my-lib like this one假设你有一个像这样的名为my-lib的 ES6 库

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

and you have to write the typescript definitions for the above library like so.并且您必须像这样为上述库编写 typescript 定义。

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

My questions is: Should the Bar class be exported?我的问题是:应该出口Bar class 吗?

If yes then by writing the following code如果是,那么通过编写以下代码

import { Bar } from 'my-lib'

will lead to declaring a Bar variable which is undefined将导致声明未定义的Bar变量

If no, then the following statement will be incorrect, since Bar is not imported如果不是,那么下面的说法是不正确的,因为没有导入 Bar

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

How should I define the Bar class so that it is exported as a type and NOT as a class?我应该如何定义Bar class 以便将其导出为类型而不是 class?

I am not sure if I understand what you're trying to achieve but if you don't want to expose your class directly but only its 'shape' (type) you can define it as an interface.我不确定我是否理解您要实现的目标,但如果您不想直接公开 class 而只公开其“形状”(类型),则可以将其定义为接口。

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

And then you import only Foo and IBar.然后你只导入 Foo 和 IBar。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM