Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 6

Writing Functions with Typed Parameters and Return Values

Recommended resources

Hello! In the previous lesson, you used string, number, and boolean to describe variables. A function uses the same types to describe what callers must provide and what they can expect back.

Today you’ll write that contract yourself. This is a small but important step toward coding independently: instead of looking at a function and guessing what it accepts, you can state its inputs and result in the code, then use TypeScript’s feedback to catch mismatches.


Give a function a clear contract

Suppose you need to calculate a membership charge from a monthly price and a number of months. A function lets you name that calculation and reuse it:

function calculateCharge(monthlyPrice: number, months: number): number {
  const total: number = monthlyPrice * months;
  return total;
}

const charge: number = calculateCharge(25, 3);
console.log(charge); // 75

Read the first line in parts. monthlyPrice and months are parameters: names for values the function will receive. Each has a number annotation. The : number after the closing parenthesis describes the return value. Inside the braces is the function body; return total sends the calculated value back to the caller.

In calculateCharge(25, 3), the values 25 and 3 are arguments. They fill the parameters in order. The call produces 75, which is assigned to charge. console.log(charge) prints that result, but printing and returning are different actions: it is the return statement that makes a value available to the caller.

Watch Net Ninja build both a regular function and an arrow function, then demonstrate what happens when a call supplies the wrong type.

TypeScript Crash Course #6 - Functions

TypeScript Crash Course #6 - Functions from Net Ninja demonstrates typed inputs, typed returns, and the errors TypeScript reports at a function call.

Watch typed parameters for the regular function’s signature and return annotation. Continue with arrow syntax to see the same contract written in another form, then checked calls to see how incompatible arguments are identified. Focus on where each annotation sits; you do not need to adopt the arrow style yet.

A type says what kind of value belongs in a parameter, not whether it makes business sense. Both calculateCharge(25, 3) and calculateCharge(25, -3) pass numbers, so the types alone cannot reject a negative duration. Handling invalid values inside a function is the focus of the next lesson.



Check the inputs and the result

A typed function gives TypeScript two places to help you. First, it checks calls against the parameter types:

calculateCharge(25, 3);     // Accepted
// calculateCharge("25", 3); // Type error: "25" is a string

Second, it checks what the body returns against the annotated return type:

function getPlanName(): string {
  return "starter"; // Accepted: this is a string
}

If getPlanName returned 42 instead, TypeScript would report a mismatch with its string return type. An explicit return annotation is useful even when TypeScript could infer the result: it records your intended contract and flags an accidental change to it.

Read the official TypeScript Handbook’s explanation to connect these two checks.

TypeScript: Documentation - Everyday Types

The TypeScript Handbook’s Everyday Types chapter shows where function annotations go and explains why an explicit return annotation can still be useful when the type is inferable.

In Functions, begin at the introductory sentence about functions passing data around. Read function annotations through Parameter Type Annotations and Return Type Annotations. Stop before Functions Which Return Promises. Pay particular attention to the difference between checking an argument at a call and checking a value returned by the function.

There is an important boundary to this protection. TypeScript checks code while you develop it; the annotations do not remain as runtime checks in the JavaScript that Node.js executes. If an API request supplies an unexpected value, a typed parameter by itself does not validate that request.



Write, run, and revise a function

Use the same project workflow as the previous lesson. Put this complete example in src/main.ts:

function makePlanLabel(planName: string, months: number): string {
  return planName + " for " + months + " months";
}

const label: string = makePlanLabel("starter", 3);
console.log(label);

Run npm run build, then npm start. The output should be:

starter for 3 months

Here, the two parameters have different types. The result is a string because the function constructs text and returns it. TypeScript can infer the type of label from the call, so its annotation is optional; the annotations on the function signature make its intended inputs and output explicit.

To see each part of the contract enforced, make these temporary changes one at a time, running npm run build after each:

  1. Change the call to makePlanLabel("starter", "3"). The second argument no longer matches the number parameter. Restore 3.
  2. Change the function’s return statement to return months;. The body now returns a number, contrary to its declared string return type. Restore the original return statement.

Rebuild successfully before running the program again. As in the previous lesson, a failed build may leave older JavaScript in dist; running that old file would not demonstrate your latest TypeScript change.

For independent practice, close or hide the finished example and retype makePlanLabel from its description: it accepts a plan name and a month count, and returns one line of text. Compare your signature with the example only after you have written it. The aim is to make the positions of the two parameter types and the return type familiar without relying on generated code.

You may also encounter the same contract written as an arrow function:

const makePlanLabel = (planName: string, months: number): string => {
  return planName + " for " + months + " months";
};

This is an alternative definition of the same function, not a new typing rule. The parameter annotations remain inside the parentheses, and the return annotation still follows them.



Conclusion

A typed function signature states the types of its parameters and its return value. TypeScript checks arguments when you call the function and checks returned values against the declared result. return gives a value back to the caller; console.log only displays something.

You can now write the contract for a straightforward calculation or text-formatting function. Next, you’ll put conditional logic inside a function so it can respond differently to valid and invalid inputs.