Tim Tim - 1 year ago 89
TypeScript Question

Using static properties with typescript, node, and babel

I am trying to create a static class property

import 'babel-polyfill';

class Test {
static name = 'abc';

which gets transpilled by typescript to


class Test {
Test.name = 'abc';

Now when I run this using babel-node, I get

TypeError: Cannot assign to read only property 'name' of function Test()

My babelrc looks like this:

"passPerPreset": true,
"presets": [
"plugins": ["transform-class-properties", "syntax-class-properties"]

Any idea what could be the error? Should the transpilled code look different (i.e. a problem with my typescript config) or am I missing yet another babel plugin?

Answer Source

The problem is the name that you chose for that static property. It conflicts with the property name of functions (which constructors and classes are) which is readonly.

Spec for property name of Function instances

Technically, name can still be replaced because the property is configurable, so it can be replaced with Object.defineOwnProperty. It's just the way transform-class-properties assigns the static properties to the constructor. It needs to use Object.defineOwnProperty and not just do the assignment like that.

Honestly, it'd be best if you avoid name, length and prototype as static class properties.