Menu
Coddy logo textTech

Typing Params & Return Values

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 22 of 73.

Functions are the building blocks of any application, and TypeScript makes them safer and more predictable by allowing you to specify exactly what types of data they accept and return. When you add type annotations to functions, you create a clear contract that defines what goes in and what comes out.

To add types to a function, you specify the type for each parameter after its name, and optionally specify the return type after the parameter list:

function greet(name: string): string {
  return "Hello, " + name;
}

function multiply(a: number, b: number): number {
  return a * b;
}

The syntax follows a simple pattern: parameterName: type for each parameter, and : returnType after the closing parenthesis.

challenge icon

Challenge

Easy

Create a function named add that takes two parameters of type number and returns their sum. The function must have an explicit return type annotation of number.

Create another function named getFullName that takes two parameters: firstName of type string and lastName of type string. The function should return the full name as a single string with a space between the first and last names. Add an explicit return type annotation of string.

Create a third function named isEligible that takes two parameters: age of type number and hasLicense of type boolean. The function should return true if the person is 18 or older AND has a license, otherwise return false. Add an explicit return type annotation of boolean.

Test your functions by calling them with the following values and printing the results:

  • Call add with 15 and 27
  • Call getFullName with "John" and "Smith"
  • Call isEligible with 20 and true
  • Call isEligible with 16 and true

Print each result on a separate line in the order specified above.

Try it yourself

// TODO: Write your code here
// Create the add function with explicit return type annotation

// Create the getFullName function with explicit return type annotation

// Create the isEligible function with explicit return type annotation

// Test the functions and print the results
// Call add with 15 and 27
// Call getFullName with "John" and "Smith"
// Call isEligible with 20 and true
// Call isEligible with 16 and true
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript