When the JavaScript compiler generates code, the type system is completely removed. There won't be any trace of T
at runtime - you need to provide an actual string value to the get()
method.
To achieve intelligent typing, create a mapping from entity names passed to doRequest()
to their corresponding entity types. Here's an example:
interface EntityMap {
JobView: JobView;
OtherEntity: OtherEntity;
EtCetera: EtCetera;
}
At runtime, there are no instances of type EntityMap
; it acts as a helper type for the compiler to understand the relationship between entity names (e.g., "JobView"
) and their types (e.g., JobView
). Interfaces excel in mapping names to types, hence our usage of them.
Your get()
method could look like this:
public get<K extends keyof EntityMap>(entityName: K) {
const response = super.doRequest("/api/fetch/" + entityName + "/123");
return response as EntityMap[K];
}
This method requires passing an entityName
parameter with a generic type K
, which must match one of the keys in EntityMap
- namely "JobView"
, "OtherEntity"
, or "EtCetera"
. At runtime, the value of entityName
is used to invoke doRequest()
, and the response is then returned as type EntityMap[K]
, where we look up the property named K
in EntityMap
.
You can utilize it like this:
const r = new RequestyThing();
const jv = r.get("JobView");
// const jv: JobView
Calling r.get("JobView")
will prompt the compiler to return a value of type JobView
.
I hope this explanation proves helpful. Best of luck!
Link to code