I have a function in which a variable is declared with a reasonably complex structure:
export function foo() {
const myVar = {
// some properties with complex types here...
}
// Do something with `myVar`
}
And now I wish to export the type of myVar so that I can use it in other files. Is there any way to get type information of scoped variables from outside the function? Something like this:
export type MyVarType = GetVariableFromFunction<typeof foo, "myVar">;
Some more context to avoid the XY problem:
I have created a TypedMessenger class. The purpose of this class is to make it easier to communicate with iframes and workers etc. It works something like this:
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 other end you create a similar TypedMessenger but with the two generic parameters flipped. And then you are able to call messenger.send("foo", 3) and it will autocomplete and type check the arguments you passed in.
Now the issue that I'm running into is that I have created a messenger inside a function, and many of these handlers use variables from the scope of that function.
const myVar: MyVarTypeinside the function to remind you to keep them in sync). Not sure how to write up an answer here, since most of the answer is contained in the question.TypedMessengeris that I didn't have to bother with writing signatures. And since I'm using JSDoc to annotate types, writing these signatures are particularly tedious, with lots of inline imports everywhere. Then again the last solution looks really messy, it's a trade-off I guess.