1

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?

Johnny Oshika
  • 54,741
  • 40
  • 181
  • 275
  • What are you gonna use the resulting type for? – kelsny Mar 16 '23 at 18:03
  • Will the class have any other properties defined outside of the constructor? – kelsny Mar 16 '23 at 18:04
  • 1
    To my eyes this is constructor version of: https://stackoverflow.com/questions/57993250/get-function-parameter-names-and-types-in-typescript - hence the answer is that it is impossible. See also: https://stackoverflow.com/questions/69687087/transform-named-tuple-to-object – Lesiak Mar 16 '23 at 18:13
  • Yeah this is impossible unless you're willing to supply a helper type like `["foo", "bar", "option"]`. You *can* detect and remove the optional properties, but if one piece of your task is impossible then the whole thing is. – jcalz Mar 17 '23 at 03:22
  • @vr it's to help with type safety in dependencies between different parts of the application. For example, one part of the application needs to save a payload into a document database. Getting type safety like this would ensure that the Class Factory used in another part of the application has all the constructor parameters it needs. – Johnny Oshika Mar 20 '23 at 16:44
  • It looks like what I asked for is not possible by reading the duplicate posts. Thanks all! – Johnny Oshika Mar 20 '23 at 16:46

0 Answers0