meyousikmann
meyousikmann

Reputation: 861

TypeScript properties

I am curious if others that are using TypeScript are also implementing properties (http://www.codingdefined.com/2015/05/get-and-set-property-in-typescript.html).

I tend to like to use properties, even in my TypeScript code, but others on my team think it is overkill. For the same reasons you have properties in C# code (Why use simple properties instead of fields in C#?), I think that properties in TypeScript are good.

This isn't an "I'm curious if other people agree with me" question, but rather I am interested in knowing if others are actually doing properties in TypeScript and why or why not. Very much like the same question asked for C# properties.

I couldn't find anyone actually asking the question for TypeScript.

Upvotes: 2

Views: 618

Answers (1)

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23532

I usually don't use them, unless I need them. The great thing is that we can start out using public variables and then add getters and setters as we need them.

So i usually start out like this:

class Test {
    testField: string = "";
}

And then when I realize I need a getter and setter, I change it to:

class Test {
    private _testField: string = null;
    get fieldName() : string {
        return this._testField;
        doSomething();
    }
    set fieldName(name : string) {
        doSomethingElse();
        this._testField = name;
    }
}

In Typescript we don't have to add getters and setters if all they're doing is getting and setting the value. This is in contrast to something like C#, where you would break the backwards compatibility by adding logic to the getter or setter.

Upvotes: 1

Related Questions