public: The public access modifier in TypeScript does not result in any changes during compilation. This is because in JavaScript, all class members are by default considered public. Therefore, a public member in a TypeScript class remains unchanged in the resulting JavaScript code.
// Example TypeScript code:
class MyClass {
public publicProperty: string;
public publicMethod(): void {
// Method implementation
}
}
// Equivalent JavaScript code after compilation:
class MyClass {
constructor() {
// Constructor implementation
}
publicMethod() {
// Method implementation
}
}
private: The private access modifier in TypeScript is compiled to JavaScript using a technique called "name mangling." This technique involves transforming the private member names by adding a prefix to make them harder to access from outside the class.
// Example TypeScript code:
class MyClass {
private privateProperty: string;
private privateMethod(): void {
// Method implementation
}
}
// Equivalent JavaScript code after compilation:
class MyClass {
constructor() {
// Constructor implementation
this._privateProperty = '';
}
_privateMethod() {
// Method implementation
}
}
In the compiled JavaScript code, the privateProperty is renamed to _privateProperty, and the privateMethod is renamed to _privateMethod. Although these names are not truly private, they serve as a convention to indicate that they are intended for internal use within the class and should not be accessed directly from outside.
It's important to note that the encapsulation provided by private in TypeScript is enforced during compile-time, but it doesn't prevent access to private members at runtime. JavaScript's nature allows bypassing private access restrictions. However, adhering to the naming conventions and documentation helps developers understand the intended usage and discourages accessing private members directly.
Good explain of "unknown vs any" in TypeScript - https://dmitripavlutin.com/typescript-unknown-vs-any/