Functions: Typing Your Logic

8 min read

In JavaScript, functions are incredibly flexible. They will take any argument you hand them, in any quantity, and return absolutely whatever they feel like returning. While this flexibility is great when you are quickly scripting a tiny project, it becomes a nightmare in a large codebase.

Imagine you are managing a logistics warehouse. If a truck arrives and the workers blindly load whatever is on the dock—whether it is delicate electronics, industrial anvils, or a live badger—without checking the shipping manifest, things are going to break.

TypeScript functions act as strict warehouse managers. They demand to know exactly what is coming in (parameters) and exactly what is going out (return values) before the code even runs. Let's break down how to properly type your logic.


1. Typing Function Parameters and Return Values

The Problem

In plain JavaScript, you might write a simple function to calculate a discount:

javascript
function applyDiscount(price, discount) {
  return price - discount;
}

If another developer (or you, three weeks later after a long weekend) calls applyDiscount("100", "20%"), JavaScript won't stop you. It will try to subtract a string from a string, return NaN (Not a Number), and suddenly your e-commerce checkout is charging customers NaN dollars.

The Solution: Explicit Typing

TypeScript solves this by letting you define the exact data types a function will accept and what it will give back.

Definition:
Parameter typing is the process of appending : type to function arguments. Return typing is appending : type after the parameter parentheses to dictate the output type.

typescript
function applyDiscount(price: number, discount: number): number {
  return price - discount;
}

// ✅ TypeScript is happy.
const finalPrice = applyDiscount(100, 20); 

// ❌ TypeScript yells: Argument of type 'string' is not assignable to parameter of type 'number'.
const brokenPrice = applyDiscount("100", "20%"); 

Industry Practice: Type Inference

Under the hood, TypeScript is incredibly smart at "guessing" (inferring) what your function returns based on the return statement.

typescript
// TypeScript automatically knows this returns a string.
function getGreeting(name: string) {
  return `Hello, ${name}`; 
}

Should you explicitly type return values?
In industry standards, it is highly recommended to explicitly type return values on major functions, even if TypeScript can infer them. Why? Because it acts as a contract. If another developer accidentally modifies the function to return a number instead of a string, TypeScript will throw an error inside the function itself, stopping the bug at the source rather than letting it ripple through the codebase.


2. Optional and Default Parameters

The Problem

JavaScript functions don't care if you pass fewer arguments than defined; it just assigns undefined to the missing ones. But TypeScript is strict. If a function asks for three arguments, it expects exactly three. What if we are building a user profile system where a user has a first name, last name, but maybe no middle name?

The Solution: The ? and = Operators

We need a way to tell TypeScript that an argument is not strictly required.

Definition:

  • Optional Parameter: A parameter suffixed with ?, indicating it can be of the specified type or undefined.
  • Default Parameter: A parameter assigned a fallback value using =, which automatically makes it optional without needing the ?.
typescript
// The '?' makes middleName optional (string | undefined)
function formatName(firstName: string, lastName: string, middleName?: string): string {
  if (middleName) {
    return `${firstName} ${middleName} ${lastName}`;
  }
  return `${firstName} ${lastName}`;
}

formatName("Ada", "Lovelace"); // ✅ Valid
formatName("John", "Doe", "William"); // ✅ Valid

Now, let's look at default parameters. Imagine a system that generates reports. If the user doesn't specify a format, we default to PDF.

typescript
// 'format' is implicitly typed as a string and becomes optional
function generateReport(data: string, format: string = "PDF"): void {
  console.log(`Generating ${format} report for: ${data}`);
}

generateReport("Sales Data"); // Outputs: Generating PDF report for: Sales Data
generateReport("Sales Data", "CSV"); // Outputs: Generating CSV report for: Sales Data

⚠️ The Golden Rule

Optional and default parameters must always come after required parameters.
If you put an optional parameter first, TypeScript will get confused when you try to call the function with missing arguments. Imagine waiting in line at a fast-food counter. The cashier asks for your side dish first (which is optional), but you just start shouting your main burger order. The system breaks down. Always ask for the required items first.


3. Rest Parameters for Variable Arguments

The Problem

Sometimes you don't know how many items you need to process. In an analytics system, you might want to log a variable number of events at once. In JavaScript, you can use the rest operator (...args) to gather all remaining arguments into an array. But how do you type an unknown quantity of items?

The Solution: Array Typing

Definition:
A rest parameter is defined using the spread syntax ... followed by the parameter name, and it is typed as an array of a specific type.

typescript
function logEvents(category: string, ...events: string[]): void {
  console.log(`Category: ${category}`);
  events.forEach(event => {
    console.log(`- Event: ${event}`);
  });
}

// You can pass as many string events as you want
logEvents("Security", "Login attempt", "Password change", "2FA enabled");

Industry Practice

Rest parameters are extremely common in wrapper functions, custom logging utilities, and mathematical operations.

typescript
// A highly practical industry example: summing numbers
function calculateTotal(...prices: number[]): number {
  return prices.reduce((total, current) => total + current, 0);
}

calculateTotal(10, 20, 30, 40); // 100

Notice how prices is strictly typed as number[]. If you try to sneak a string into that list of prices, the strict warehouse manager (TypeScript) will instantly reject the shipment.


4. Understanding 'void' and 'never' Types

The Problem

Not every function produces a useful value. Some functions exist purely to execute a side effect, like manipulating the DOM, saving to a database, or printing a log. Furthermore, some functions are designed to never finish executing at all (like an infinite event-listening loop, or a function that always throws an error). JavaScript implicitly returns undefined in both scenarios. TypeScript introduces specific types to distinguish between them for better code safety.

The Solution: 'void' and 'never'

Definition:

  • void: A type representing the absence of a return value. It is used when a function completes its execution normally but returns nothing.
  • never: A type representing values that never occur. It is used for functions that will literally never reach the end of their execution block.

The void Type

You will use void constantly in UI development (like React) for event handlers.

typescript
// This function finishes its job and goes home, handing you nothing back.
function saveToDatabase(data: string): void {
  console.log("Saving...", data);
  // No return statement here.
}

Fun fact: A function returning void can technically return undefined, but assigning void is a signal to other developers (and the compiler) saying, "Hey, don't try to use the result of this function, it's useless."

The never Type

never is the drama queen of TypeScript. When a function is typed as never, it makes a solemn vow that it will crash your current execution context or run until the heat death of the universe.

typescript
// Scenario 1: Throwing an error stops execution.
function crashApplication(errorMessage: string): never {
  throw new Error(`CRITICAL FAILURE: ${errorMessage}`);
}

// Scenario 2: An infinite loop.
function keepListening(): never {
  while (true) {
    // Listen for server events forever
  }
}

Why use never?

In enterprise systems, never is incredibly useful for Exhaustive Type Checking.
Imagine you have an app that handles user roles ("Admin" | "User"). You write an if/else block to handle both. If someone later adds a "Guest" role but forgets to update your if/else block, a never type check at the end of the block will instantly trigger a compilation error, warning you that unhandled cases exist. It acts as a tripwire against future bugs.


Summary Cheat Sheet

Concept Syntax When to use it?
Return Type (x): string => Explicitly defining what a function outputs.
Optional Param name?: string When a parameter isn't required by the logic.
Default Param tax: number = 0.2 When you want a fallback value if one isn't provided.
Rest Param ...args: number[] When handling an unknown number of identical argument types.
Void (): void => Functions that do things (side-effects) but don't return data.
Never (): never => Functions that throw fatal errors or run in infinite loops.

Further Reading & References 📚

To dive deeper into the official specifications and edge cases, check out the official TypeScript documentation:

Challenge

Your task is to define the signatures for two TypeScript functions, configureSystem and throwFatalError, based on the requirements below. You only need to write the function signatures and a required type alias; do not implement the function bodies.

First, define a type alias named SystemConfig for an object that must contain two properties:

  • retries: a number
  • logging: a boolean

Next, create the configureSystem function signature with the following parameters in this specific order:

  1. A required parameter config of type SystemConfig.
  2. A required parameter hostname of type string.
  3. A parameter port of type number with a default value of 8080.
  4. An optional parameter apiKey of type string.
  5. A rest parameter plugins that accepts any number of additional string arguments.

The configureSystem function should be typed to indicate that it does not return any value.

Finally, create the throwFatalError function signature:

  1. It must accept one parameter errorMessage of type string.
  2. This function's purpose is to always throw an error, so it should be typed to indicate that it never successfully completes execution.

Expected result

Your code should correctly define a type alias SystemConfig and the signatures for the two functions, configureSystem and throwFatalError, matching all specified type annotations, parameter order, and return types.

typescript
type SystemConfig = {
  retries: number;
  logging: boolean;
};

function configureSystem(config: SystemConfig, hostname: string, port: number = 8080, apiKey?: string, ...plugins: string[]): void;

function throwFatalError(errorMessage: string): never;
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.