Back to JavaScript
2026-04-115 min read

TS Functions (JavaScript)

Learn TS Functions (JavaScript) step by step with clear examples and exercises.

Title: Mastering TypeScript Functions - A full guide to JavaScript's Statically Typed Cousin

Why This Matters

TypeScript, a statically typed superset of JavaScript, has gained popularity for its ability to catch errors during development rather than at runtime. One of the key features that make TypeScript powerful is its support for functions, which we will explore in this lesson. Understanding TypeScript functions will help you write more robust and maintainable code, especially when working on large projects or collaborating with other developers.

Prerequisites

Before diving into TypeScript functions, it's essential to have a good understanding of the following:

  1. Basic JavaScript concepts (variables, data types, operators, control structures)
  2. Intermediate JavaScript concepts (closures, prototypes, modules)
  3. Familiarity with the JavaScript ecosystem and tools like Node.js
  4. A text editor or Integrated Development Environment (IDE) that supports TypeScript, such as Visual Studio Code
  5. Basic understanding of static typing principles and their benefits in programming
  6. Knowledge of how to install and configure TypeScript in your project

Core Concept

TypeScript functions are similar to their JavaScript counterparts but come with added benefits due to TypeScript's static typing system. Here are the key elements of a TypeScript function:

  1. Function declaration:
function functionName(parameters: types[]): returnType {
// function body
}
  1. Function expression:
const functionName = (parameters: types[]): returnType => {
// function body
};
  1. Anonymous functions (using arrow syntax):
const functionName = (parameters: types[]): returnType => {
// function body
};

TypeScript Function Signatures

A TypeScript function signature consists of the function name, parameters, and return type:

  • Function Name: A unique identifier for the function.
  • Parameters: Zero or more comma-separated variables that receive input values when the function is called. Each parameter should have a specified data type.
  • Return Type: The data type of the value that the function returns (optional). If not specified, TypeScript infers the return type based on the code within the function body.

Function Types

TypeScript has several built-in function types:

  1. (parameters: types[]): returnType: A regular function type with a specific set of parameters and return type.
  2. () => returnType: A function type that takes no parameters and returns a specific value.
  3. (parameter: type) => returnType: A function type that accepts one parameter of a specific data type and returns a specific value.
  4. (...parameters: types[]) => returnType: A function type that accepts any number of arguments of specified data types and returns a specific value.

TypeScript Function Calls

Calling a TypeScript function is similar to calling a JavaScript function, with the added advantage of static typing:

function addNumbers(num1: number, num2: number): number {
return num1 + num2;
}

const result = addNumbers(5, 7); // TypeScript infers the types correctly
console.log(result); // Output: 12

Type Inference and Explicit Typing

TypeScript can infer data types based on the context of your code. However, it's often a good practice to explicitly specify the data types for better readability and maintainability:

let userName: string = "John Doe"; // Explicitly typed variable

function greet(name: string): void {
console.log("Hello, " + name);
}

greet(userName); // TypeScript infers the correct types for the function call

Worked Example

Let's create a simple TypeScript program that calculates the area of a rectangle using a function:

  1. Create a new file called rectangleArea.ts.
  2. Add the following code to define a calculateRectangleArea function and call it with specific values:
function calculateRectangleArea(length: number, width: number): number {
return length * width;
}

const length: number = 5;
const width: number = 7;
const area: number = calculateRectangleArea(length, width);
console.log(`The area of the rectangle is ${area}`); // Output: The area of the rectangle is 35

Common Mistakes

  1. Forgetting to return a value: If a function doesn't explicitly return a value and has a specified return type, TypeScript will throw an error.
  2. Mismatched parameter types: TypeScript checks the data types of parameters at compile-time, so make sure they match the expected types.
  3. Not specifying return types: Although TypeScript can infer return types based on the code within the function body, it's a good practice to explicitly specify them for better readability and maintainability.
  4. Using undefined or null where a specific type is expected: TypeScript allows you to catch these errors at compile-time by using strict null checks (--strictNullChecks) and ensuring that variables are initialized before use.
  5. ### Common Mistakes - Subheadings
  • Improperly handling optional parameters: When defining optional parameters, ensure they have a default value and are marked with the ? symbol.
  • Not using interfaces for function types: Interfaces can help enforce specific function signatures across your codebase.
  • Ignoring type narrowing: TypeScript offers type narrowing techniques like in, instanceof, and typeof to improve type safety.

Practice Questions

  1. Write a TypeScript function called calculateCircleArea that takes the radius as a parameter and returns the circle's area using the formula πr².
  2. Create a TypeScript function called greetMultipleUsers that accepts an array of user names as a parameter and logs a personalized greeting for each user.
  3. Write a TypeScript function called calculateFactorial that calculates the factorial of a number (e.g., 5! = 5 × 4 × 3 × 2 × 1).
  4. ### Practice Questions - Subheadings
  • Type-safe event handling: Implement an event handler in TypeScript that ensures the event object has the correct properties and types.
  • Type guarding: Use type guards to improve the type safety of your functions by checking for specific conditions within the function body.
  • Using interfaces for custom types: Create a custom interface for a Person object and define a function that accepts an array of Person objects and calculates their combined age.

FAQ

  1. What happens if I don't specify return types in my TypeScript functions?

TypeScript can infer the return types based on the code within the function body, but it's a good practice to explicitly specify them for better readability and maintainability.

  1. Can I use TypeScript with JavaScript libraries or frameworks like React or Angular?

Yes! TypeScript is designed to work seamlessly with JavaScript libraries and frameworks. You can gradually convert your existing projects to TypeScript or start new ones using TypeScript from the beginning.

  1. Do I need to install TypeScript separately, or is it included in Node.js?

TypeScript is not included by default in Node.js, but you can easily install it as a package using npm (Node Package Manager). To do this, run npm install -D typescript in your project directory.

  1. ### FAQ - Subheadings
  • Why should I use TypeScript over JavaScript?

TypeScript offers several benefits over JavaScript, including static typing, better tooling support, and improved code maintainability. It also catches errors during development rather than at runtime.

  • How can I migrate an existing JavaScript project to TypeScript?

You can gradually convert your existing JavaScript project to TypeScript by using TypeScript's compatibility mode and converting files one by one. Tools like ts-migrate can help automate the process.

  • What are some popular Integrated Development Environments (IDEs) for TypeScript?

Popular IDEs for TypeScript include Visual Studio Code, WebStorm, and JetBrains' IntelliJ IDEA. These tools offer features like code completion, error detection, and refactoring assistance.

TS Functions (JavaScript) | JavaScript | XQA Learn