My goal is to generate a new object type that inherits all the properties from an existing class instance. In other words, I am looking for a way to transform a class instance into a plain object.
For example, consider the following scenario:
class Foobar {
foo: number = 0;
bar(): void {}
}
type ClassProperties<C extends new(...args: readonly unknown[]) => unknown> =
C extends new(...args: readonly unknown[]) => infer R
? { [K in keyof R]: R[K] }
: never
;
const foobar = new Foobar();
const data: ClassProperties<typeof Foobar> = { ...foobar };
However, when I try to implement this, TypeScript throws an error saying
Property 'bar' is missing in type '{ foo: number; }' but required in type '{ foo: number; bar: () => void; }'
.
I find this issue puzzling since it appears to be a straightforward task. Is there a reliable solution to this problem?
Any insights would be highly appreciated.