Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A public getter in TypeScript is an accessor method defined with the get keyword and the public access modifier that intercepts read operations on a class property. It allows a method to be accessed syntactically as a standard property while executing underlying logic to compute or retrieve the returned value.
class ClassName {
    public get propertyName(): ReturnType {
        // execution logic
        return value;
    }
}

Technical Characteristics

Visibility and Access The public modifier exposes the member to the public API of the class instance, meaning it can be accessed externally via class instances, by derived subclasses, and internally within the class. Because TypeScript class members are public by default, the explicit public keyword is optional but often used for strict stylistic adherence. Parameter Constraints A getter cannot accept any parameters. Attempting to define a parameter in a get accessor will result in a compiler error (TS1094: A 'get' accessor cannot have parameters). Type Inference and Return Types TypeScript automatically infers the type of the exposed property based on the getter’s return type. While a getter is conceptually designed to return a value, TypeScript allows getters without a return statement (which implicitly infers a return type of void), provided the noImplicitReturns compiler flag is not enabled. If a corresponding set accessor is defined for the same property name, the return type of the getter must be assignable to the parameter type of the setter. Readonly Inference If a public getter is defined without a corresponding setter, TypeScript automatically infers the property as readonly at the type level. Any attempt to assign a value to this property will throw a compilation error (TS2540: Cannot assign to 'propertyName' because it is a read-only property). Compilation Target Getters are an ECMAScript feature. The TypeScript compiler requires the --target flag to be set to ES5 or higher to support accessors. When the compilation target is set to ES5, get accessors are transpiled into Object.defineProperty() calls utilizing the get property descriptor. When targeting ES6 (ES2015) or higher, TypeScript preserves the native ECMAScript class get syntax.

Mechanical Example

class SensorData {
    private _rawInput: number = 25;

    // Explicitly typed public getter
    public get normalizedInput(): number {
        return this._rawInput * 1.5;
    }
}

const sensor = new SensorData();

// The getter is accessed via property dot-notation, omitting parentheses
const data = sensor.normalizedInput; 

// Error TS2540: Cannot assign to 'normalizedInput' because it is a read-only property.
// sensor.normalizedInput = 50; 
Master TypeScript with Deep Grasping Methodology!Learn More