-1

I want to use a variable outside a function without using global variable.
After searching, I found this answer working: https://stackoverflow.com/a/8819001
It works perfectly but it raises error in Typescript.
Is there any way to eliminate this error?
You can run this code here and see:
https://www.typescriptlang.org/play?#code/DYUwLgBAZg9jC8AKAlPAfAbwFAVxUkAdgIYC2I8A5ANIAiAQpTnrDAHTEBGAxvCeVgC+WViizcYhAM4xQbYDADmiVhx7IsQA

let foo=()=>{
    let name='KDB'
    foo.abc=name
}
foo()
console.log(foo.abc)```

1 Answer 1

1

You'll need to declare a type for the function - type it as not only a void function, but also one that intersects with { abc: string }.

let foo: (() => void) & { abc?: string } = () => {
    let name = 'KDB'
    foo.abc = name
}
foo()
console.log(foo.abc)

That said, this is a pretty smelly pattern, especially in TypeScript. If your goal is:

without using global variable

then just make sure you aren't on the top level, and declare a variable named name.

(() => {
    let name!: string;
    const foo = () => {
        name = 'KDB'
    };
    foo();
    console.log(name);
})();

Or have foo return the string - that'd be even better, if it can fit into your actual use case.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Yeah, I know it is a little weird but I have to use in this manner. By the way, can you explain (or link where I can read) why we are using '?' and '!' ? I only know basic typescript.
The ! is needed to tell TypeScript that the variable definitely will be assigned to by the time you reference it later. (Without that, it'll throw an error.) The ?: on the function tells TS that the property is optional - that it may either be a string, or it may be undefined. (That allows the function to be defined without the property initially being on the function.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.