A private setter in TypeScript is a class member configuration where theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
set accessor is assigned a more restrictive access modifier (private or protected) than its corresponding get accessor. Introduced in TypeScript 4.3, this feature allows a property to be publicly readable during static analysis while restricting mutation strictly to the internal lexical scope of the class.
Syntax
To implement a private setter, apply theprivate (or protected) keyword directly to the set method declaration, while leaving the get method with a broader visibility modifier (typically public).
Technical Constraints and Rules
- Visibility Hierarchy: The access modifier on the setter must be strictly more restrictive than the modifier on the getter. A
publicgetter can pair with aprotectedorprivatesetter. Aprotectedgetter can pair with aprivatesetter. You cannot define aprivategetter with apublicsetter. - Implicit Getter Visibility: If no access modifier is explicitly defined on the getter, it defaults to
public. The setter must then explicitly declare its narrower scope. - Type Compatibility: While TypeScript 4.3+ allows getters and setters to have different types, the type returned by the getter must be assignable to the type accepted by the setter.
- Compile-Time Enforcement: The
privatekeyword is a TypeScript-specific construct. The access restriction is enforced entirely by the TypeScript compiler during static analysis. - Runtime Erasure: Upon compilation to JavaScript, the
privatemodifier is erased. The resulting JavaScript will output standardgetandsetfunctions on the class prototype. Because JavaScript property descriptors cannot have mixed runtime visibility, the setter remains publicly accessible at runtime.
ECMAScript Runtime Equivalent
To achieve strict runtime encapsulation that mirrors the behavior of a TypeScript private setter, you cannot use theprivate set syntax, as it exposes the setter in the emitted JavaScript. Instead, you must omit the set accessor entirely—making the property strictly read-only from the outside—and mutate an ECMAScript private field (#) directly from within internal class methods.
Master TypeScript with Deep Grasping Methodology!Learn More





