Tutorials Logic, IN info@tutorialslogic.com

TypeScript Functions: Parameters, Return Types and Callbacks

TypeScript Functions

Functions are where most application rules live: they calculate values, validate input, call APIs, transform data, and connect modules together. TypeScript helps by checking both sides of a function: what the caller is allowed to pass and what the function promises to return.

In plain JavaScript, a function can accidentally receive a string where a number was expected and the bug may appear much later. In TypeScript, parameter and return types make the contract visible at the function boundary, so mistakes are caught while coding.

Add one worked example that compares the normal path with the boundary case for TypeScript Functions: Parameters, Return Types and Callbacks.

TypeScript Functions Parameters Return Types and Callbacks should be studied as a practical TypeScript lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the typescript > functions page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

Why Function Types Matter

A Typed Function Contract

A Typed Function Contract
function calculateDiscount(price: number, percent: number): number {
  const discountAmount = (price * percent) / 100;
  return price - discountAmount;
}

const finalPrice = calculateDiscount(1200, 15);
console.log(finalPrice); // 1020

// calculateDiscount("1200", 15);
// Error: the first argument must be a number.

Parameter Types and Return Types

Each parameter can have its own type annotation. The return type is written after the parameter list. TypeScript can often infer the return type, but explicit return types are useful for public functions, controller helpers, service functions, and shared utilities.

An explicit return type also catches missing return paths. If a function says it returns a number, TypeScript will complain when one branch returns nothing or returns a different type.

Return Type Checking

Return Type Checking
type InvoiceLine = {
  label: string;
  quantity: number;
  unitPrice: number;
};

function getLineTotal(line: InvoiceLine): number {
  return line.quantity * line.unitPrice;
}

function getInvoiceTotal(lines: InvoiceLine[]): number {
  return lines.reduce((total, line) => total + getLineTotal(line), 0);
}

const total = getInvoiceTotal([
  { label: "Hosting", quantity: 1, unitPrice: 499 },
  { label: "Support", quantity: 2, unitPrice: 250 },
]);

console.log(total); // 999

Optional and Default Parameters

Use ? when a parameter is truly optional. Inside the function, an optional parameter has the type you wrote plus undefined, so your code should handle the missing case before using it.

Default parameters are often better when the function has a sensible fallback. A default value keeps the call simple while still giving the function a real value to work with internally.

Feature Syntax Best Use
Required parameter name: string The caller must provide the value.
Optional parameter name?: string The value may be missing and must be checked.
Default parameter name = "Guest" The function can provide a fallback itself.

Optional Versus Default Parameters

Optional Versus Default Parameters
function greet(name: string, title = "Developer"): string {
  return `Hello ${name}, ${title}`;
}

function formatPhone(countryCode: string, number?: string): string {
  if (!number) {
    return countryCode;
  }

  return `${countryCode}-${number}`;
}

console.log(greet("Asha")); // Hello Asha, Developer
console.log(greet("Asha", "Team Lead")); // Hello Asha, Team Lead
console.log(formatPhone("+91", "9876543210")); // +91-9876543210

Function Type Expressions

A function type expression describes the shape of a function value. It is useful when you pass callbacks, store functions in objects, or expose a hook-style API where callers provide behavior.

The syntax looks like an arrow function: parameters on the left and the return type on the right. The parameter names are documentation for developers, while the parameter types are what TypeScript checks.

Callback Function Type

Callback Function Type
type ScorePredicate = (score: number) => boolean;

function filterScores(scores: number[], predicate: ScorePredicate): number[] {
  return scores.filter(predicate);
}

const passed = filterScores([35, 72, 91], score => score >= 40);
const excellent = filterScores([35, 72, 91], score => score >= 90);

console.log(passed); // [72, 91]
console.log(excellent); // [91]

Typing Object Methods

Objects often contain methods. You can type those methods directly in an object type or interface. This is common in service objects, repositories, validators, and UI event handlers.

When a method belongs to a typed object, TypeScript checks both the method implementation and every place that calls it. This keeps related data and behavior aligned.

Object Method Types

Object Method Types
type User = {
  id: number;
  name: string;
  isActive: boolean;
};

type UserFormatter = {
  label(user: User): string;
  status(user: User): "active" | "inactive";
};

const formatter: UserFormatter = {
  label(user) {
    return `#${user.id} - ${user.name}`;
  },
  status(user) {
    return user.isActive ? "active" : "inactive";
  },
};

console.log(formatter.label({ id: 1, name: "Ravi", isActive: true }));

Void, Never and Unknown in Functions

Some functions are called for their side effect rather than their returned value. Use void when a function does not return a useful value, such as a logger or event handler.

Use never for functions that cannot finish normally, such as functions that always throw an error. Use unknown for input from the outside world, then narrow it before using it.

Special Function Return Types

Special Function Return Types
function logMessage(message: string): void {
  console.log(`[app] ${message}`);
}

function fail(message: string): never {
  throw new Error(message);
}

function parseId(value: unknown): number {
  if (typeof value === "number") {
    return value;
  }

  if (typeof value === "string" && value.trim() !== "") {
    return Number(value);
  }

  return fail("Invalid id value");
}

TypeScript Functions Parameters Return Types and Callbacks in Real Work

TypeScript Functions Parameters Return Types and Callbacks matters in TypeScript because it changes how a program is written, tested, or debugged. The page should explain the normal flow first: what the developer writes, what the runtime or platform does, and what result should appear.

When teaching TypeScript Functions Parameters Return Types and Callbacks, avoid stopping at syntax. Show the surrounding decision: why this feature is chosen, what problem it removes, and what would become harder if the feature were not used.

  • Identify the concrete problem solved by TypeScript Functions Parameters Return Types and Callbacks.
  • Show the normal input, operation, and output for typescript.
  • Mention the nearby alternative a beginner may confuse with this topic.
  • Tie the explanation to a real project task, command, component, query, or debugging step.

TypeScript Functions Parameters Return Types and Callbacks normal path trace

TypeScript Functions Parameters Return Types and Callbacks normal path trace
1. Define the input for TypeScript Functions Parameters Return Types and Callbacks.
2. Apply the rule from the lesson.
3. Compare the actual result with the expected result.
4. Record the fix if the result differs.

TypeScript Functions Parameters Return Types and Callbacks edge path trace

TypeScript Functions Parameters Return Types and Callbacks edge path trace
1. Try empty, missing, duplicate, or invalid data.
2. Identify where TypeScript Functions Parameters Return Types and Callbacks changes behavior.
3. Explain the safest correction.
4. Retest the normal path.
Key Takeaways
  • Function types describe both what callers can pass and what the function returns.
  • Use explicit return types for shared functions, public APIs, and important business logic.
  • Optional parameters must be handled because they can be undefined.
  • Function type expressions are ideal for callbacks and reusable behavior.
  • void, never, and unknown help model side effects, impossible returns, and external input.
Common Mistakes to Avoid
WRONG Memorizing TypeScript Functions Parameters Return Types and Callbacks without the situation where it is useful.
RIGHT Connect TypeScript Functions Parameters Return Types and Callbacks to a concrete TypeScript task.
Purpose makes syntax easier to recall.
WRONG Testing TypeScript Functions Parameters Return Types and Callbacks only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to TypeScript Functions Parameters Return Types and Callbacks.
Evidence keeps debugging focused.
WRONG Memorizing TypeScript Functions Parameters Return Types and Callbacks without the situation where it is useful.
RIGHT Connect TypeScript Functions Parameters Return Types and Callbacks to a concrete TypeScript task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to TypeScript Functions: Parameters, Return Types and Callbacks, then fix it and explain the fix.
  • Summarize when to use TypeScript Functions: Parameters, Return Types and Callbacks and when another approach is better.
  • Write a small example that uses TypeScript Functions Parameters Return Types and Callbacks in a realistic TypeScript scenario.
  • Change one important value in the TypeScript Functions Parameters Return Types and Callbacks example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in TypeScript, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.