Extract public interface of a class
05:45 06 Aug 2020

Is there a mapped type that lets you extract the public properties and methods of a TypeScript class into an interface? It would look like this:

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

type FooPublic = PublicInterface;

In this example, FooPublic would have the property y and the method bar(), but would not have private x or private baz().

The closest I have come is:

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

However, this doesn't appear to correctly type the methods. I get no error if I say:

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