Typescript Functions: Exploring TypeScript Function Type

What is a function in TypeScript?

A function in TypeScript serves as the foundation for code that is easy to read, maintain, and use again. A function is essentially a collection of instructions designed to accomplish a particular task.

You can specify the type of parameters and the return value in a function.

TypeScript Function Type

A function is executed when it is called. Here are some key points about TypeScript functions:

Defining a Function

A function definition outlines the steps and methods for accomplishing a particular task.

You need to define a function before you can use it. We use the keyword “function” to define functions.

Syntax:

The standard way to define a function is shown below

function  function_name() { 
   // function body 
}

Example:

function greet(name: string): void {
    console.log(`Hello, ${name}.  Welcome to Itsourcecode!`);
}

In our example, greet is the function name, name is the parameter of type string, and the statements inside the function form the body of the function.

The function prints a greeting message when it’s called with a name.

For example, calling greet(“Anna”) would print “Hi, Anna. Welcome to Itsourcecode!”. The void keyword indicates that this function does not return any value.

Calling a Function

To run a function, you need to call it. This is known as invoking the function.

Syntax

Function_name()

Example

// Define the function
function greet(name: string): void {
    console.log(`Hello, ${name}. Welcome to Itsourcecode!`);
}

// Call the function
greet("Anna");

Output:

Hello, Anna. Welcome to Itsourcecode!

Returning Functions

Functions can also give back a value when they are done. These are known as returning functions.

Syntax

function functionName(parameters): returnType {
    // function body
    // ...
    return value; // value should be of type returnType
}

  • functionName is the name of the function.
  • parameters are the input to the function.
  • returnType is the type of value the function returns.
  • value is the actual value that the function returns.

Example

function sayHello(name: string): string {
    let message = `Hello, ${name} Welcome to Itsourcecode!`;
    return message;
}

let greeting = sayHello("Anna");
console.log(greeting);

Output:

Hello, Anna Welcome to Itsourcecode!

Parameterized Function

Parameters are a way to send values into functions. They are part of the function’s unique signature.

When a function is called, values for these parameters are provided.

Unless stated otherwise, the count of values given should align with the number of parameters the function has.

When invoking a function, two methods exist to provide arguments to a function.

  1. Pass by Value

This approach takes the actual value of an argument and copies it into the function’s formal parameter. In this scenario, any modifications made to the parameter within the function don’t impact the original argument.

  1. Pass by Reference

This approach takes the address of the argument and copies it into the function’s formal parameter. Within the function, this address is used to access the original argument.

This implies that any changes made to the parameter inside the function will affect the original argument.

Optional Parameters

Optional parameters come into play when it’s not necessary to provide arguments for a function to run.

You can designate a parameter as optional by adding a question mark to its name.

The optional parameter should be positioned as the final argument in a function.

Here’s how you would declare a function with an optional parameter:

function greet(name: string, greeting?: string) {
    if (greeting) {
        return `${greeting}, ${name}!`;
    } else {
        return `Hello, ${name}!`;
    }
}

console.log(greet("Anna")); 
console.log(greet("Bea", "Welcome to Itsourcecode"));

Output:

Hello, Anna!
Welcome to Itsourcecode, Bea!

We can make parameters optional in TypeScript by appending a question mark (?) to the parameter name in the function signature. Here’s an example:

function greet(name: string, greeting?: string) {
    if (greeting) {
        return `${greeting}, ${name}!`;
    } else {
        return `Hello, ${name}!`;
    }
}

As you can see in our example, greeting is an optional parameter. If a value for greeting is not provided when the function is called, it will be undefined, and the function will return “Hello, ${name}!”.

If a value is provided, the function will return ${greeting}, ${name}!.

Default Parameters

Default parameters allow us to set a default value for a parameter. If we don’t provide a value for a default parameter when calling the function, it uses the default value.

Syntax:

function function_name(param1[:type],param2[:type] = default_value) { 
}

Here’s an example:

function greet(name: string, title: string = "Mr."): void {console.log(Hello, ${title} ${name}!);}

In this example, the title is a default parameter with a default value of “Mr.”.

Named Parameters

TypeScript doesn’t natively support named parameters, but we can achieve a similar effect using object literals.

Here’s an example:

function greet({ name, title }: { name: string; title: string; }): void {
console.log(Hello, ${title} ${name}!);
}

In this example, we’re passing an object to the function and destructuring it in the function signature.

Rest Parameters

Rest parameters in programming are like open invitations you can pass as many values as you want to a function.

The catch is, all these values should be of the same kind.

Think of rest parameters as a bucket that can hold multiple items, but only of one type.

When you’re declaring a rest parameter, you put three dots before its name. And remember, if there are other parameters, they should come first, before this ‘open invitation’ or rest parameter.

Rest parameters allow a function to accept any number of arguments.

Here’s an example:

function greet(name: string, …titles: string[]): void {
let fullTitle = titles.join(' ');
console.log(Hello, ${fullTitle} ${name}!);
}

In this example, …titles is a rest parameter. It captures all remaining arguments passed to the function.

Void Return Type

void in TypeScript is used when a function doesn’t return a value.

Here’s an example:

function sayHello(name: string): void {
console.log(Hello, ${name}!);
}


In this example, sayHello is a function that doesn’t return any value (its return type is void).

Type Alias

A type alias in TypeScript gives a name to a type.

Here’s an example:

type StringFunction = (s: string) => void;

let greet: StringFunction;
greet = function(name: string): void {
console.log(Hello, ${name}!);
}

In this example, StringFunction is a type alias for a function type.

Anonymous Function

Functions without a specific name, known as anonymous functions, are created dynamically while the program is running.

Like any other function, they can take in inputs and produce outputs. However, once they’re created, they typically can’t be accessed again.

This is a unique characteristic of anonymous functions.

An anonymous function can be assigned to a variable. This kind of assignment is known as a function expression.

Syntax

var res = function( [arguments] ) { ... }

Example:


let greet = function(website) {
    return `Hi welcome to ${website}!`;
}

console.log(greet("Itsourcecode"));

Output:

Hi welcome to Itsourcecode!

Here’s an example of an anonymous function with parameters in TypeScript:

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

console.log(addNumbers(15, 5));

Output:

20

The Function Constructor

You can also create a function using JavaScript’s built-in Function constructor in TypeScript.

This is another way to define functions in TypeScript.

Syntax

var res = new Function( [arguments] ) { ... }.

Example

let addNumbers = new Function('num1', 'num2', 'return num1 + num2');

console.log(addNumbers(10, 20)); 

Output

30

Conclusion

In conclusion, we’ve explored the fundamentals of functions in TypeScript.

From defining functions and specifying parameter types to more advanced topics like optional parameters, default parameters, and rest parameters, we’ve seen how functions serve as essential building blocks for structured, reusable, and maintainable code.

We’ve also looked at different return types, type aliases, anonymous functions, and the Function constructor.

I hope that this tutorial has helped you a solid understanding of TypeScript functions and their versatility.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment