代码之家  ›  专栏  ›  技术社区  ›  Auth Infant

为什么从其他模块引用的函数有时未定义,但后来定义了?

  •  0
  • Auth Infant  · 技术社区  · 7 年前

    export function bar(): void { }
    

    然后,我在另一个模块中定义一个引用该函数的映射,并尝试如下使用它:

    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
    }
    

    但是,如果我改为(毫无意义地)从“test”方法内部设置完全相同的值,如下所示:

    function test(): void {
        myMap.set(0, bar);
    
        const method = myMap.get(0);
    
        // now 'method' is no longer undefined
    

    相关的(我想?),如果我改为这样定义我的映射:

    const myMap = new Map<number () => void>([
        [0, () => baz()],
    ]);
    

    …但保持“test”不变,然后定义“method”,并从“test”中调用它成功地调用baz()。

    为什么我看到这种行为?Typescript如何处理模块导入,以便导入的方法在定义myMap时未定义,但在运行test()时可用?或者我误解了如何正确定义地图?

    0 回复  |  直到 7 年前
    推荐文章