0

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 Answers1

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 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. – Abdul Azeem Aug 27 '22 at 17:04
  • 1
    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.) – CertainPerformance Aug 27 '22 at 17:17