Tim Tim - 2 months ago 9
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

require("babel-polyfill");

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": [
"react",
"es2015",
"stage-0"
],
"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

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.

Comments