Files
it-know-how/typescript/bits/13-optional-params-and-default-values.md
T
2026-03-27 12:58:01 +01:00

739 B
Executable File

Optional Parameters and Default Values in TypeScript

In TypeScript, a function parameter can be optional and can also have a default value.

Example from your code

function buildWeeklyDownloadPeriods(
  dateRange?: DownloadDateRange,
  now = new Date(),
): string[] {
  // ...
}

What this means

  • dateRange?:
    • The ? means this argument is optional.
    • The caller can omit it.
  • now = new Date():
    • If caller does not pass now, TypeScript uses new Date().

Python comparison

def build_weekly_download_periods(date_range=None, now=None):
    if now is None:
        now = datetime.now()

TypeScript default parameters are cleaner because the default is declared directly in the signature.