I'm writing a TypeScript app which takes two numbers and prints the sum of the numbers to the console.
calculator2.ts
:
export namespace calculator
{
export function add(a: number, b: number): number
{
return a + b;
}
export function subtract(a: number, b: number): number
{
return a - b;
}
}
app.ts
:
import {calculator} from './calculator2';
var answer = calculator.add(3, 4);
console.log('Answer: ' + answer);
I ran tsickle to transpile the TypeScript to JavaScript that the Google Closure Compiler understands. Then I ran the Closure Compiler with the advanced optimization flag to minify my code.
This is the output (pretty-printed):
var a;
(function(d) {
d.add = function(b, c) {
return b + c;
};
d.a = function(b, c) {
return b - c;
};
})(a || (a = {}));
var e = a.add(3, 4);
console.log("Answer: " + e);
This prints 7, just as expected, but the calculator.subtract()
(d.a
in the minified code) is not removed, while I'm not using it.
If I modify the calculator
file like this:
export var calculator: any =
{
add: function(a: number, b: number): number
{
return a + b;
},
subtract: function(a: number, b: number): number
{
return a - b;
}
};
The Closure Compiler outputs this:
console.log("Answer: 7");
Is there a way to tell the Closure Compiler that the subtract
function is not called (at least not from app.ts
) and that it can be removed?
Another test:
Using 'calculator3.ts'
export class calculator
{
public add(a: number, b: number): number
{
return a + b;
}
public subtract(a: number, b: number): number
{
return a - b;
}
}
and 'app.ts'
import {calculator} from './calculator3';
var myCalculator = new calculator();
var answer = myCalculator.add(3, 4);
console.log('Answer: ' + answer);
generates:
var c = (new (function() {
function a() {
}
a.prototype.add = function(a, b) {
return a + b;
};
return a;
}())).add(3, 4);
console.log("Answer: " + c);
Which removes the subtract
function, but is not optimized to console.log("Answer: 7")
(which is not necessary, but would be great)