Parameter Properties Declare Constructor Fields
Declare constructor parameter properties with private, public, and protected modifiers, then read the generated instance fields.
Code
// 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
Properties File ParserParse Java .properties files with comments, continuations, separators, and escapes, then emit clean JSON.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.