4

Am I right that public members in a TypeScript constructor are public in the class and that private members are private?

If so, what is the effective difference between public members and properties?

Assuming that the difference is that properties can act more like c# properties (that is, can have code associated with their access) why would you want to make a field public, without the protections inherent in making it a property?

Jesse Liberty
  • 1,314
  • 1
  • 11
  • 26

2 Answers2

5

private creates a field and public creates a property.

This is not like a C# property, in fact what makes it a property is just that it is public. There are no accessors.

Jesse Liberty
  • 1,314
  • 1
  • 11
  • 26
  • can you give more clarity on field and property here. – Khurshid Ansari Jan 31 '19 at 07:22
  • Hey, I see field / property explanation not clear enough. But this is RESULTS based explanation: https://kendaleiv.com/typescript-constructor-assignment-public-and-private-keywords/ give it a check – Alexis Rengifo Aug 19 '21 at 00:04
  • But based in [this](https://www.typescriptlang.org/docs/handbook/2/classes.html ) article above, the @jesse-liberty explanation totally makes sense. – Alexis Rengifo Aug 19 '21 at 00:08
2

Let's first see the C# class then we will convert it into TypeScript:

public class Car {
    private int _x;
    private int _y;
    public Car(int x, int y)
    {
        this._x = x;
        this._y = y;
    }
}

Means _x and _y cannot be accessed from out of the class but can be assigned only through the constructor, if you want to write the same code in TypeScript it will be:

class Car {
    constructor(private _x: number, private _y: number) {}
}

If you have worked with TypeScript, you can notice we use this keyword to access these variables.

If it is only the parameter then what is the meaning of using this._x OR this._y out of constructor in the class, because it creates member variables as well.

Here is the JavaScript code generated from above TypeScript code:

var Car = (function () {
    function Car(_x, _y) {
        this._x = _x;
        this._y = _y;
    }
    return Car;
})();

this._x and this._y are moved inside another function, which means Car object cannot access it but you can initiate and assign the new Car(10, 20).

Ali Adravi
  • 21,707
  • 9
  • 87
  • 85