My goal is to minimize redundancy in common code patterns within a project by setting up TypeScript to perform a sort of enchantment - deducing a generic type based on the existence of a function with a specific name.
Picture me utilizing a framework that includes a getStuff
function with the following structure:
function getStuff<T> (): T {}
Please note that getStuff()
does not accept any arguments, so why/how can it include a generic type? Well, in this framework, thanks to some mystical framework magic, it will actually return the value from another function named loadStuff
found in the same file.
function loadStuff () {
return { a: 1, b: 2 }
}
function something () {
const stuff = getStuff()
if (stuff.a === 1) ... // true
}
The issue arises because TypeScript is unaware of this framework sorcery, hence the need for the generic provided by the framework.
To add typing to stuff
, I have to manually provide a hint using the generic attached to getStuff
.
const stuff = getStuff<{ a: number, b: number }>()
if (stuff.a === 'hello') ... // excellent, now I receive auto-completion on .a and a type error
What I aim to accomplish is to eliminate the need to constantly provide this manual hint to getStuff
each time by utilizing a global configuration.
In simple terms, what I wish to convey to TypeScript is that, universally within this project, when I utilize getStuff<T>
, automatically populate <T>
with the return type of a function located at the top scope of the same file (module) named loadStuff
.
I am content with having these specific names for loadStuff
and getStuff
that must be adhered to precisely.
I acknowledge that I could achieve this through code generation, but I would much prefer to avoid that route if possible. It would be fantastic if TypeScript could be configured 'magically' to handle this dynamically and globally for the entire project. Is this achievable?