Snæbjørn Snæbjørn - 2 months ago 4x
TypeScript Question

TypeError when class has static member `name`

I have the following TypeScript class

module Test {
"use strict";

class Foo {
public static name = "foo";

Pretty simple.

But when run in Chrome I get the following error:

Uncaught TypeError: Cannot assign to read only property 'name' of function 'function Foo() { }'

Here's the generated javascript:

var Test;
(function (Test) {
"use strict";
var Foo = (function () {
function Foo() {
} = "foo";
return Foo;
})(Test || (Test = {}));

If I use a different name then
I don't get an error.

module Test {
"use strict";

class Foo {
public static huh = "foo";

What is going on?


The problem seems to be that you are trying to write to In the code that you wrote initially, you can see in the compiled code that you are changing

Consider just this code

  function Foo(){}
  console.log(; // prints 'Foo'

The error is because you are trying to change this function's property, and are not allowed to do so (read-only property ..). More information about why (and how) you are not allowed to do so can be found here. Thanks to @ssube for providing this link in the comments

So whilst you have not created that property yourself, all your functions do actually have it. You can check this page for some more information.