Skip to content

Instantly share code, notes, and snippets.

@rjmunro
Last active January 9, 2023 16:12
Show Gist options
  • Save rjmunro/428ec644b6e53a499ca3a5ba8de2edc7 to your computer and use it in GitHub Desktop.
Save rjmunro/428ec644b6e53a499ca3a5ba8de2edc7 to your computer and use it in GitHub Desktop.
Typescript weirdness
var a = require('./module1');
var b = require('./module2');
// import a from './module1';
// import b from './module2';
console.log('a',a);
console.log('b',b);
let foo = 'hello1';
module.exports = foo;
let foo = 'hello2';
module.exports = foo;
{
"name": "tstest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/node": "^7.0.0",
"typescript": "^2.1.5"
}
}
{
"compilerOptions": {
"outDir": "build"
},
"exclude": [
"node_modules",
"build"
]
}
@rjmunro
Copy link
Author

rjmunro commented Jan 18, 2017

Output:

$ bin/tsc
module1.ts(1,5): error TS2451: Cannot redeclare block-scoped variable 'foo'.
module2.ts(1,5): error TS2451: Cannot redeclare block-scoped variable 'foo'.
$ node build/index.js 
a hello1
b hello2

So the compiler throws an error but emits working code anyway.

If you comment out one of the let foo = .. lines, typescript's warnings go away, but the code it emits doesn't run. (I've commented line 1 of module2.ts below:

$ bin/tsc
$ node build/index.js 
/Users/rjmunro/personal_projects/tstest/build/module2.js:2
module.exports = foo;
                 ^

ReferenceError: foo is not defined
    at Object.<anonymous> (/Users/rjmunro/personal_projects/tstest/build/module2.js:2:18)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/rjmunro/personal_projects/tstest/build/index.js:2:9)
    at Module._compile (module.js:571:32)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment