Reputation: 1021
I making a simple typescript application and it is throwing error step by step like,
Code:
app.ts
function add(a,b){
return a + b;
}
const result = add('10','5');
console.log(result);
Error 1:
Cannot redeclare block-scoped variable 'result'.
Solution 1:
Included export {}
in app.ts
like,
export {}
function add(a,b){
return a + b;
}
const result = add('10','5');
console.log(result);
which also compile the js file like,
"use strict";
exports.__esModule = true;
function add(a, b) {
return a + b;
}
var result = add('10', '5');
console.log(result);
This results in error at browser like,
Uncaught ReferenceError: exports is not defined at app.js:2
Please help me how can I fix this issue? Also added tsconfig.json
file but that also didn't help it throws error like,
/@types/express/index.d.ts' not found.
Typescript version: Version 3.8.3
Upvotes: 1
Views: 1959
Reputation: 301
I faced this error in simple typescript app too.In order to solve that after searching for an hour, I came up with this solution:
adding this line of code to index.html file.This makes the error go away.
<script>var exports = {};</script>
Upvotes: 1
Reputation: 36
The reason you have the error in the first place might be because TS is picking up the compiled file as well and is assuming the result is being redefined as it sees 2 files declaring the same global variable.
Scripts create global variables when you use var
(to which the const
may transpile to) and function
. Modules don't do that.
TypeScript assumes the file is a script if it doesn't have export or import statements. So adding the export {}
makes the error go away.
However, you're using the default module system in TS, which is CommonJS
, so the file is transpiled assuming there's an exports
object in it's scope. That would be the case in NodeJS
, but not the browser.
If you change the tsconfig.json to have module: "ES2015"
or module: "ESNext"
, the compiler will use import and export statements instead, which work in the browser if the entry point is defined with <script type="module" src="...
.
Upvotes: 0
Reputation: 13539
simply export it as it is:
function add(a: string, b: string) {
return a + b;
}
const result = add('10','5');
export { result };
Upvotes: 0