Back to Course

Learn TypeScript

0% Complete
0/0 Steps
Lesson 13 of 25
In Progress

Function Return Types and Parameter Types

In TypeScript, you can specify the return type of a function using a type annotation. The return type specifies the data type of the value returned by the function.

For example:

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

console.log(greet('John')); // Outputs: "Hello, John!"

In this example, we have defined a function named “greet” that takes a single parameter “name” of type “string” and returns a “string”. We have specified the return type of the function using the “: string” type annotation after the parameter list.

You can also specify the return type using the “void” type to indicate that the function does not return a value. For example:

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

printGreeting('John'); // Outputs: "Hello, John!"

In this example, we have defined a function named “printGreeting” that takes a single parameter “name” of type “string” and returns “void”. The function body logs a greeting to the console but does not return a value.

Function Parameter Types

In TypeScript, you can specify the type of each parameter in a function using a type annotation. The parameter type specifies the data type of the value passed to the function as an argument.

For example:

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

console.log(greet('John')); // Outputs: "Hello, John!"

In this example, we have defined a function named “greet” that takes a single parameter “name” of type “string”. The “name” parameter must be passed a value of type “string” when the function is called.

You can specify multiple parameters in a function, each with its own type annotation. For example:

function add(x: number, y: number): number {
  return x + y;
}

console.log(add(1, 2)); // Outputs: 3

In this example, we have defined a function named “add” that takes two parameters “x” and “y” of type “number”. The “x” and “y” parameters must be passed values of type “number” when the function is called. The function returns the sum of “x” and “y”.

Optional Parameters

Optional parameters are a useful feature in TypeScript as they allow you to define a function with parameters that are not always required. This can be useful when you want to provide default values for certain parameters or when you want to allow the caller to choose which parameters to specify.

For example:

function greet(name: string, greeting?: string): string {
  return `${greeting || 'Hi'}, ${name}!`;
}

console.log(greet('John')); // Outputs: "Hi, John!"
console.log(greet('John', 'How are you doing')); // Outputs: "How are you doing, John!"

In this example, we have defined a function named “greet” that takes a single required parameter “name” of type “string” and an optional parameter “greeting” of type “string”. If the “greeting” parameter is not specified when the function is called, the default value of “Hi” is used.

You can also specify default values for optional parameters using the “= defaultValue” syntax. For example:

function greet(name: string, greeting: string = 'Hi'): string {
  return `${greeting}, ${name}!`;
}

console.log(greet('John')); // Outputs: "Hi, John!"
console.log(greet('John', 'How are you doing')); // Outputs: "How are you doing, John!"

In this example, we have defined a function named “greet” that takes a single required parameter “name” of type “string” and an optional parameter “greeting” of type “string” with a default value of “Hi”. If the “greeting” parameter is not specified when the function is called, the default value of “Hi” is used.

Rest Parameters

In TypeScript, you can use a rest parameter to specify a variable number of arguments in a function. The rest parameter is defined using the “…” syntax and must be the last parameter in the function’s parameter list.

For example:

function add(...numbers: number[]): number {
  let result = 0;
  for (const number of numbers) {
    result += number;
  }
  return result;
}

console.log(add(1, 2, 3, 4, 5)); // Outputs: 15

In this example, we have defined a function named “add” that takes a variable number of arguments of type “number” and returns the sum of those numbers. The “numbers” parameter is defined as a rest parameter using the “…” syntax and is of type “number[]”. The function uses a loop to iterate over the “numbers” array and adds each number to the “result” variable.

Function Overloading

Function overloading is a useful feature in TypeScript as it allows you to define multiple versions of a function that can be called with different argument types. This can be useful when you want to provide different implementations of a function based on the type of the arguments.

For example:

function greet(name: string): string;
function greet(age: number): string;
function greet(value: string | number): string {
  if (typeof value === 'string') {
    return `Hello, ${value}!`;
  } else {
    return `You are ${value} years old`;
  }
}

console.log(greet('John')); // Outputs: "Hello, John!"
console.log(greet(30)); // Outputs: "You are 30 years old"

In this example, we have defined a function named “greet” that has three declarations. The first declaration specifies a single parameter “name” of type “string” and a return type of “string”. The second declaration specifies a single parameter “age” of type “number” and a return type of “string”. The third declaration specifies a single parameter “value” of type “string” or “number” and a return type of “string”.

The function body contains a conditional statement that checks the type of the “value” parameter and returns a different greeting based on the type. If “value” is of type “string”, the function returns a greeting using the “name” parameter. If “value” is of type “number”, the function returns a greeting using the “age” parameter.

You can call the “greet” function with either a “string” or a “number” argument and the correct version of the function will be called based on the type of the argument.

Conclusion

In conclusion, function return types and parameter types are an important aspect of TypeScript programming. They allow you to specify the data types of function arguments and return values, as well as provide optional and rest parameters and use function overloading. Understanding and properly using these features will help you write more reliable and maintainable code in your TypeScript projects.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Write a function named “sum” that takes an array of numbers and returns the sum of those numbers. Use a type annotation to specify the parameter and return types.

function sum(numbers: number[]): number {
  let result = 0;
  for (const number of numbers) {
    result += number;
  }
  return result;
}

console.log(sum([1, 2, 3, 4, 5])); // Outputs: 15

Write a function named “greet” that takes a string and an optional boolean parameter and returns a greeting based on the string and boolean value. Use type annotations to specify the parameter and return types.

function greet(name: string, isFormal: boolean = false): string {
  if (isFormal) {
    return `Hello, ${name}!`;
  } else {
    return `Hi, ${name}!`;
  }
}

console.log(greet('John')); // Outputs: "Hi, John!"
console.log(greet('John', true)); // Outputs: "Hello, John!"

Write a function named “calculateSum” that takes a variable number of numbers and returns the sum of those numbers. Use a rest parameter and a type annotation to specify the parameter and return types.

function calculateSum(...numbers: number[]): number {
  let result = 0;
  for (const number of numbers) {
    result += number;
  }
  return result;
}

console.log(calculateSum(1, 2, 3, 4, 5)); // Outputs: 15

Write a function named “greetPerson” that takes a string and returns a greeting based on the string. Use function overloading and type annotations to specify the parameter and return types.

function greetPerson(name: string): string;
function greetPerson(age: number): string;
function greetPerson(value: string | number): string {
  if (typeof value === 'string') {
    return `Hello, ${value}!`;
  } else {
    return `You are ${value} years old`;
  }
}

console.log(greetPerson('John')); // Outputs: "Hello, John!"
console.log(greetPerson(30)); // Outputs: "You are 30 years old"

Write a class named “Person” that has three private properties: “name”, “age”, and “phoneNumber”. Add getters and setters for each property and use type annotations to specify the types.

class Person {
  private _name: string;
  private _age: number;
  private _phoneNumber: string;

  get name(): string {
    return this._name;
  }

  set name(value: string) {
    this._name = value;
  }

  get age(): number {
    return this._age;
  }

  set age(value: number) {
    this._age = value;
  }

  get phoneNumber(): string {
    return this._phoneNumber;
  }

  set phoneNumber(value: string) {
    this._phoneNumber = value;
  }
}

const person = new Person();
person.name = 'John';
person.age = 30;
person.phoneNumber = '123-456-7890';
console.log(person.name); // Outputs: "John"
console.log(person.age); // Outputs: 30
console.log(person.phoneNumber); // Outputs: "123-456-7890"