Monday, August 21, 2023

TypeScript: make interface from class, with ChatGPT help

I was looking to create an interface that extends a TypeORM class;
the issue with this was that class has many methods, and we need only fields (props), no methods.
Did Google search, StackOverflow... no simple solution...
Then I "asked" ChatGPT, and sure enough it provided a useful answer, it works in this case!

final solution:

type ITable1Fields = Omit<InstanceType<typeof DbTable1>, keyof DbTable1>;

prompt:
in typescript how to get interface with fields from a class without methods

In TypeScript, you can use the typeof operator along with the InstanceType utility type to extract the shape of a class into an interface without methods. Here's an example:

typescript
Copy code
class MyClass {
  id: number;
  name: string;

  constructor(id: number, name: string) {
    this.id = id;
    this.name = name;
  }

  method1() {
    // Some code...
  }

  method2() {
    // Some code...
  }
}

type MyClassFields = Omit<InstanceType<typeof MyClass>, keyof MyClass>;

// MyClassFields will have the shape of { id: number; name: string; }
In the above example, the MyClass class has two properties (id and name) and two methods (method1 and method2). We use the InstanceType utility type to get the instance type of the class. Then we use the Omit utility type to exclude the keys that belong to the keyof MyClass type (i.e., the methods). The resulting type MyClassFields will only contain the fields of the class without the methods.