Search code examples
typescriptfileimportnested

How do I call a nested function from another file in typescript


file1:

export func foo1 {
    const foo2 { return something}
    return foo1something
}

I just want to test this foo2 individual function in my test file:

file2:

import { foo1 } from '../file1';

Now how do I access foo2 here?


Solution

  • Your Import looks fine and the problems does not relate to "different files" or the "import".

    let and const or nested functions are block-scoped so they cannot be accessed outside of the original function.

    they are only available in the nested function (the block-scope).

    You can call the inner function inside the oute function itself.

    export function foo() {
        console.log('foo');
        function bar() {
            return `bar`;
        }
        return bar()
    }
    
    console.log(foo());
    

    result: foo bar

    You can declare a object or class with nested functions or methods as properties and call it from the "outside":

    File1:

    export const someObject = {
      foo: () => { console.log('foo') },
      bar: () => { console.log('bar') }
    }
    

    File2:

    import { someObject } from "./File1";
    
    someObject.foo();
    someObject.bar();
    

    result: foo bar