Typescript提取类的公共接口

时间:2020-08-06 10:25:02

标签: typescript types interface

是否有一种映射类型可以让您将Typescript类的公共属性和方法提取到接口中?看起来像这样:

class Foo {
  private x: number;
  public y: number;
  
  bar(a: number) {}
  
  private baz() {}
}

type FooPublic = PublicInterface<Foo>;

在此示例中,FooPublic具有属性y和方法bar(),但是没有private xprivate baz()

我最接近的是:

type PublicInterface<T> = {[K in keyof T]: T[K]};

但是,这似乎不能正确键入方法。如果我说:我没有错误

const example: PublicInterface<Foo> = {
  y: 5,
  bar() {}  // Incorrect - should require an integer argument!
}

0 个答案:

没有答案