5. Parameter Types, Default Values & Return Signatures

Typing Functions in TypeScript

// Explicit parameter types and return type:
function calculateTimeout(retries: number, baseTimeout: number = 5000): number {
  return baseTimeout * (retries + 1);
}

// Optional parameter (?):
function logResult(testName: string, durationMs?: number): void {
if (durationMs !== undefined) {
console.log(${testName} finished in ${durationMs}ms);
} else {
console.log(${testName} finished);
}
}

// Async function return signature: always Promise<T>
async function fetchToken(apiUrl: string): Promise<string> {
return "auth_token_xyz";
}

Task

  • Create a function `retryAction` with:
  • parameter `actionName` of type `string`
  • parameter `maxAttempts` of type `number` with default value `3`
  • return type `string` that returns `"${actionName} configured with ${maxAttempts} attempts"`.
πŸ’‘Common doubts
Did you like the problem?
Lesson 5 of 36
TypeScript
Loading code editor…
Next