If I define a function in foo.ts like this:
export function bar(): void { }
Then I define a map that refers to that function in a different module and try to use it like this:
import { bar } from './foo'
const myMap = new Map<number, () => void>([
[0, bar],
]);
function test(): void {
const method = myMap.get(0);
// at this point here, 'method' is undefined
}
However, if I instead (nonsensically) set the exact same value from inside the 'test' method like this:
function test(): void {
myMap.set(0, bar);
const method = myMap.get(0);
// now 'method' is no longer undefined
Relatedly (I think?), if I instead define myMap like this instead:
const myMap = new Map<number () => void>([
[0, () => baz()],
]);
...but keep 'test' the same, then 'method' is defined and calling it from within 'test' successfully calls baz().
Why am I seeing this behavior? Is there something about how Typescript handles module importing such that the imported methods are not defined when myMap is defined but are available when test() is running? Or am I misunderstanding how to define the map correctly?
Thanks!
Aucun commentaire:
Enregistrer un commentaire