Skip to main content
An abstract getter in TypeScript is an accessor declaration within an abstract class that enforces a contract for a property’s retrieval without providing an implementation. It mandates that any concrete subclass must provide a specific implementation for that getter, ensuring strict type adherence and structural conformity across derived classes.

Syntax

An abstract getter is defined using the abstract modifier followed by the get keyword. It must terminate with a semicolon rather than a block statement.

Implementation Mechanics

When a concrete class extends an abstract class containing an abstract getter, the TypeScript compiler enforces the following rules:
  1. Context Restriction: Abstract getters can only exist inside classes marked with the abstract keyword.
  2. No Implementation Body: The declaration cannot contain curly braces {} or any return logic.
  3. Type Covariance: The return type of the implemented getter in the subclass must be assignable to the return type defined in the abstract base class.

Resolution Methods

TypeScript’s structural typing system allows a subclass to fulfill an abstract getter contract in multiple ways. An abstract getter simply enforces that a property is readable; it does not restrict the property from being writable, nor does it inherently represent a read-only state. Method 1: Concrete Getter The subclass implements a standard get accessor with a function body.
Method 2: Standard Mutable Property Because an abstract getter only dictates that a value must be readable, a standard mutable property perfectly satisfies the structural contract.
Method 3: Readonly Property A readonly property also satisfies the contract, as it fulfills the requirement of being readable while explicitly preventing reassignment at the subclass level.

Interaction with Abstract Setters

If an abstract getter is paired with an abstract setter, the subclass must provide a mutable implementation. A readonly property will no longer satisfy the contract.
Note: In TypeScript 4.3 and later, the type of the abstract setter’s parameter can be wider than the abstract getter’s return type, provided the getter’s type is assignable to the setter’s type.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More