cruzan
cruzan

Reputation: 357

Private constructor variables and public getters for TypeScript classes

I come from C# background. Most of my classes are designed to be immutable. I was wondering if it is good practice to use private constructor variables and public getters for accessing data in TypeScript classes.

For example:

class UnitType {
   constructor(private code: string, private name: string, private unitType: string) {

}

get Code(): string {
    return this.code;
}
get Name(): string {
    return this.name;
}
get UnitType(): string
    return this.unitType;
}

I cannot seem to find any examples of TypeScript code like above. Am I missing something?

Upvotes: 2

Views: 6988

Answers (2)

engineforce
engineforce

Reputation: 3020

You can use the public readonly keyword to simplify your class to:

class UnitType {
    constructor(
        public readonly code: string, 
        public readonly name: string, 
        public readonly unitType: string) {
    }
}

// Usage:
var type1 = new UnitType("a", "b", "c");

// error TS2450: Left-hand side of assignment expression cannot be a constant or a read-only property.
type1.code = "aa";

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135762

Yes, it is a good practice. Encapsulation is always a good thing: it diminishes the "mistake surface" and lowers cognitive load on the programmers (less stuff - public, visible - to worry about).

Though you could emulate private properties with ES5, that doesn't come in a natural/trivial or very readable way (some alternatives even incur in performance penalties). So you won't see much code like that around because JavaScript itself does not have private modifiers.

Also, the properties marked as private in typescript are private just at compile-time. Since their runtime is JavaScript, which, as said, doesn't know what private is, they will be accessible.

Upvotes: 1

Related Questions