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)```
CodePudding user response:
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.