series0ne series0ne - 1 month ago 10
Javascript Question

How to create value properties in TypeScript

TypeScript has a built in feature for defining accessor properties

class Test {
constructor(private value: number = 123) {
}

public get Value(): number {
return this.value;
}

public set Value(value: number) {
this.value = value;
}
}


Compiler output

var Test = (function () {
function Test(value) {
if (value === void 0) { value = 123; }
this.value = value;
}
Object.defineProperty(Test.prototype, "Value", {
get: function () {
return this.value;
},
set: function (value) {
this.value = value;
},
enumerable: true,
configurable: true
});
return Test;
})();


JavaScript also supports value properties

Object.defineProperty(someObj, "MyValueProperty", {
// The key here is value as opposed to get and set.
value: 5
enumerable: true,
configurable: false
});


How do you define value propertes with TypeScript?

NOTICE: I notice that I'm being pointed to another stackoverflow question regarding TypeScript getters and setters. This is not what I want. I want to know how to create properties that implement
value
, not
get
and
set
!

Answer

You could do the following:

class Test {
    Value : number;
}

Object.defineProperty(Test.prototype, "Value", {
    value: 5,
    enumerable: true,
    configurable: false
});

var t = new Test();
t.Value = 54;
console.log(t.Value); // 5

But why not just return the value in the get function?

class Test {
    public get Value(): number {
        return 5;
    }
}

var t = new Test();
t.Value = 54;
console.log(t.Value); // 5

Using Decorators

A more elegant way if you really want a value property is to create a reusable decorator:

function ValueProperty(value: any) {
    return (target: Object, propertyKey: string) => {
        Object.defineProperty(target, propertyKey, {
            value,
            enumerable: true,
            configurable: false
        });
    };
}

Then to use it:

class Test {
    @ValueProperty(5)
    Value: number;
}

new Test().Value; // 5
Comments