如何在 TypeScript 中从另一个文件中调用嵌套函数

huangapple go评论64阅读模式
英文:

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

问题

file1:

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

file2:

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

现在我怎么在这里访问foo2
英文:

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?

答案1

得分: 1

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 outer function itself.

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

console.log(foo());

result:
foo
bar

You can declare an 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

英文:

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

huangapple
  • 本文由 发表于 2023年5月11日 02:35:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76221628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定