1

Is there a way to accomplish this Node.js/CommonJS syntax with TypeScript?

const makeObservable = exports.makeObservable = function _makeObservable(fn: any, opts: any) {}

Basically as you can see, would like to declare a local variable on the same line as exporting that variable. Is it possible in strict TS?

5
  • Does this not work?: export function foo() { return 'bar'; } Commented Jan 11, 2017 at 6:17
  • right but would you be able to call foo() locally (in the same file)? With the syntax in the question, you can call the function locally and it's exported. Commented Jan 11, 2017 at 6:18
  • 1
    Have a try and look at the compiled JavaScript: typescriptlang.org/play/index.html. I would expect you can invoke the function within the same file. Commented Jan 11, 2017 at 6:22
  • yeah it looks like it works, but for some reason with the typescriptlang.org website, I can only convert to AMD Commented Jan 11, 2017 at 6:27
  • typescriptlang.org/play/… Commented Jan 11, 2017 at 6:27

1 Answer 1

1

When exporting a named function, the compiled Javascript first defines the named function. You should be able to invoke the named function within the same file:

Example:

export function foo() {
    return 'bar';
}

const baz = foo();
console.log(baz);

compiles to CommonJS:

"use strict";
function foo() {
    return 'bar';
}
exports.foo = foo;
var baz = foo();
console.log(baz);  // bar
Sign up to request clarification or add additional context in comments.

Comments