I want to create a generic TypeScript object type who's properties are composed of required arguments of a class constructor. For example, if I had this class:
class Example {
constructor(
public readonly foo: string,
public readonly bar: number,
public readonly option?: number,
) {}
}
I'd like a type (or interface) like this:
type ExampleArgs = {
foo: string,
bar: number
}
I'd like it to be generic so the type will be inferred from any class.
I got close with this:
type ConstructorArgs<T> = T extends new (...args: infer Args) => any
? Required<{ [K in keyof Args]: Args[K] }>
: never;
But that creates an array type. Using it like this:
type ExampleArgs = ConstructorArgs<typeof Example>; // [foo: string, bar: number, option: number]
Will result in: [foo: string, bar: number, option: number]
What I'd like to do is drop the optional option
argument and transform the type into an object. Is that possible?