Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving function names when generating JavaScript from TypeScript

Tags:

typescript

Currently, when you compile something like the following TypeScript program:

class Foo {
    Bar(): void {}
}

it generates the following JavaScript:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.Bar = function () { };
    return Foo;
}());

The Bar method is declared as an anonymous function. Is there any way to make TypeScript generate Bar as a named function? I'd prefer something like the following:

var Foo = (function () {
    function Foo() {
    }
    Foo.prototype.Bar = function Bar() { };
    return Foo;
}());

This would make it possible to do proper inspection of method names at runtime.

Update

After opening this issue on TypeScript's github repo, I got a response stating that:

This is actually an ES6 spec compliance problem since ES6 class method names do get populated as expected.

The issue was added as a bug, so it appears the TypeScript team will be adding support for preserving function names.

like image 320
Beevik Avatar asked May 26 '26 05:05

Beevik


1 Answers

If you don't mind about the methods being assigned to the instance instead of the prototype then you can do this:

class Foo {
    Bar = function Bar(): void { }
}

Which will compiled to:

var Foo = (function () {
    function Foo() {
        this.Bar = function Bar() { };
    }
    return Foo;
}());
like image 94
Nitzan Tomer Avatar answered May 27 '26 21:05

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!