I am facing a challenge with a function where I have declared a variable with a somewhat complex structure:
export function foo() {
const myVar = {
// some properties with complex types here...
}
// Do something with `myVar`
}
Now, I want to export the type of myVar
so that I can utilize it in other files. Is there a way to obtain type information of scoped variables from outside the function? Something similar to this:
export type MyVarType = GetVariableFromFunction<typeof foo, "myVar">;
Providing additional context to avoid the XY problem:
I have developed a TypedMessenger
class. This class is aimed at simplifying communication with iframes and workers. It functions as follows:
import type {TheirHandlers} from "./worker.ts";
const myHandlers = {
foo(x: number) {
return x;
,
bar() {
return "hello";
},
};
export type MyHandlers = typeof myHandlers;
const messenger = new TypedMessenger<TheirHandlers, MyHandlers>();
messenger.setResponseHandlers(myHandlers);
On the recipient end, you create a similar TypedMessenger
but with the two generic parameters flipped. Subsequently, you can use messenger.send("foo", 3)
to trigger autocompletion and type checking for the arguments passed in.
The issue arises as I have instantiated a messenger within a function, and several handlers within it rely on variables from the function's scope.