Within my class, I have a static method:
class Application {
static get(): string {
...
}
}
Now I need to use this static get method in another class. I am aware that I can achieve this by:
class Caller {
klass: { get (): typeof Application["get"] }
}
This process is straightforward when the method does not require any arguments. Note: Please see below for why this assumption is incorrect
However, if I decide to add an argument:
class Application {
static get(argument: string): string {
...
}
}
...I am then forced to modify the Caller
class (as well as any other classes with similar signatures):
class Caller {
klass: { get (argument: string): typeof Application["get"] }
}
Is there a way to avoid this repetitive task? It's clear that the klass.get
always mirrors the function signature of Application.get
. Can TypeScript be informed in some way about this relationship?
class Caller {
klass: { get (signature of typeof Application["get"]): typeof Application["get"] }
}
Note: The earlier approach was actually incorrect: I had mistakenly defined get()
to return something akin to typeof Application["get"]
.
I made a new attempt with the following solution:
class Caller {
klass: {
[Key in keyof typeof Application]: typeof Application[Key]
}
}
...however, I still need to confirm whether this resolves the issue, will check on it.
Note 2: Both methods appear to be viable:
// reference all properties
class Caller {
klass: {
[Key in keyof typeof Application]: typeof Application[Key]
}
}
// or if only one specific thing is needed
// reference one property
class Caller {
klass: {
get: typeof Application["get"]
}
}
Regrettably, things become more complex if the referenced method, such as get()
, interacts with static properties within Application
. In such cases, TypeScript may raise concerns about these properties not being found (if only the method is referenced and not every property).
Therefore, referencing all properties seems like the safest approach to take.