Objective: Retrieve the type from a neighboring field or function parameter. The type of this field/parameter is then stored in an array and treated as a generic.
class Resource<T> {
value: T;
constructor(
dependencies?: Resource<any>[],
initFunction?: ((dependencyValues: any[]) => void)
) {
// ...
}
}
const dep1 = new Resource<string>();
const dep2 = new Resource<number>();
const r = new Resource<boolean>(
[dep1, dep2],
(deps) => {
// Current scenario:
// deps: any[]
// Desired outcome with real types:
// deps: [string, number]
}
);
The same objective can be approached differently by using a configuration object instead of constructor parameters.
class Resource<T> {
constructor(config?: ResourceConfig<T>) {
// ...
}
}
interface ResourceConfig<T> {
dependencies?: Resource<any>[];
init?: ((dependencyValues: any[]) => void);
}
So, how can this be achieved?
P.S. While I could manually specify the type of parameters like deps: [string, number]
, my goal is to automatically obtain the required types without manual intervention every time.
I have tried various approaches, including inferring types, but have been met with challenges where the preprocessor still defaults to any
or unknown
for these fields.