Parameter Properties Declare Constructor Fields

Declare constructor parameter properties with private, public, and protected modifiers, then read the generated instance fields.

TypescriptConfig Management

Code

typescriptsnippet
23 lines
// Parameter properties declare instance fields from constructor arguments.
class HttpClient {
  constructor(
    private readonly baseUrl: string,
    public readonly timeoutMs = 5_000,
    protected readonly retries = 2,
  ) {}

  describe(): string {
    return this.baseUrl + ' timeout=' + this.timeoutMs + ' retries=' + this.retries;
  }
}

class AdminClient extends HttpClient {
  showRetries(): number {
    return this.retries;
  }
}

const client = new HttpClient('https://api.example.com', 2_500);
console.log(client.describe());
console.log('public field:', client.timeoutMs);
console.log('protected field:', new AdminClient('https://admin.example.com').showRetries());

How it works

The private readonly baseUrl / public readonly timeoutMs / protected readonly retries constructor parameters each become an instance field, describe() reads all three, and AdminClient.showRetries() proves retries is visible to subclasses.

Module-level bindings hold the data — client — with no function scope in between.

Applying it

Each run prints the 2 labeled blocks public field:, protected field: in source order.

Statements that matter

return this.baseUrl + ' timeout=' + this.timeoutMs + ' retries=' + this.retries;

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `client`.