denoland / deno

A modern runtime for JavaScript and TypeScript.
https://deno.com
MIT License
98.09k stars 5.4k forks source link

In TypeScript, private property can be accessible from outside #27019

Closed ACAlexChen closed 3 days ago

ACAlexChen commented 3 days ago

Version: Deno 2.1.1

class A {
  private a = 1
  public b = 2
}

const a = new A()
console.log(a.a) // 1
console.log(a.b) // 2

Property 'a' should be only accessible within class 'A' But when I run this code with Deno, still can be accessible from outside

ACAlexChen commented 3 days ago

{ED656CFB-825C-418B-A17D-6AF34D3252CB}

nathanwhit commented 3 days ago

Property privacy in typescript is enforced only in typechecking, it has no runtime effect. If you want truly private properties, you probably want this. Those are enforced both when typechecking and on execution

dsherret commented 3 days ago

See right hand side of screenshot of JavaScript output.

image

As mentioned by Nathan, what you want to use is JS private properties (see class B above using #): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties