Typing Functions

Parameters, optional arguments, and explicit return types.

TypeScript3 min readConcept 18 of 54

The core of your logic

In TypeScript, you can add types to both the input parameters of a function and the output value (the return type).

This guarantees that the function receives what it expects, and the caller receives what was promised.

Preventing silent mistakes

If you don't explicitly type the return value, TypeScript will infer it based on what you return. While inference is smart, explicit return types are safer.

An explicit return type prevents you from accidentally returning early or returning the wrong variable due to a typo.

Syntax

typescript // 1. Parameter Types & Explicit Return Type function calculateTax(amount: number, rate: number): number { return amount * rate; } // 2. Optional Parameters (?) // The 'message' parameter can be string or undefined function log(id: number, message?: string): void { console.log(id, message); }

Try it

Toggle the ? optional flag to see how it affects the function signature and the compiler's strictness.

msg parameter:
function greet(
name: string,
msg?: string
): string {
// ...
}

// Calling the function
greet("Alice");

Compile Success

Because msg is marked with ?, it is perfectly valid to call the function with only one argument.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why does TypeScript throw an error if you define 'function setConfig(url?: string, port: number)'?

Remember this

  • Type parameters by adding : Type after the parameter name.
  • Type the return value by adding : Type after the parentheses.
  • Make parameters optional by adding a ? before the colon.
  • Optional parameters must always be at the end of the signature.

Done with this concept?

Mark it complete to track your progress. No login needed.