Parameters and Return Types in TypeScript
Learn how to pass values to functions using parameters, define parameter types, return values from functions, and use TypeScript return type annotations.
What Will We Learn?
Functions can accept inputs, perform operations, and return results. TypeScript allows us to specify the types of parameters and return values to make function usage clearer and safer.
- Understand parameters and arguments.
- Declare parameters with specific types.
- Return values from functions.
- Specify function return types.
- Use multiple parameters in practical programs.
Parameters and Return Types Workflow
Follow these steps to understand how a function accepts input and returns a result.
Step 1
Pass ArgumentsProvide input values in the function call.
Step 2
Receive ParametersStore input values in parameters.
Step 3
Process DataExecute the required operation.
Step 4
Return ResultReturn the result when required.
1. Function Parameters in TypeScript
Parameters are variables declared in a function definition. They receive values supplied when the function is called.
Syntax
function functionName(parameter: type): void {
// Function statements
}
Example
function greetStudent(name: string): void {
console.log("Welcome, " + name);
}
greetStudent("Rahul");
Expected Output
Welcome, Rahul
Explanation
-
nameis the function parameter. -
stringspecifies that the parameter accepts a string value. -
"Rahul"is the argument passed to the function.
2. Function with Multiple Parameters
A function can accept multiple parameters. Each parameter can have its own data type.
Example
function displayStudent(
name: string,
age: number,
course: string
): void {
console.log("Name:", name);
console.log("Age:", age);
console.log("Course:", course);
}
displayStudent("Priya", 22, "TypeScript");
Expected Output
Name: Priya
Age: 22
Course: TypeScript
Explanation
The function accepts three parameters: a string for the student's name, a number for age, and a string for the course.
Arguments must be supplied in the corresponding parameter order when calling this function.
3. Difference Between Parameters and Arguments
Parameters and arguments are related, but they have different meanings.
Example
function add(a: number, b: number): number {
return a + b;
}
console.log(add(10, 20));
Explanation
| Term | Example | Meaning |
|---|---|---|
| Parameters | a and b |
Variables declared in the function definition. |
| Arguments | 10 and 20 |
Actual values passed when calling the function. |
Expected Output
30
4. Function Return Type
A return type specifies the type of value a function returns. It is written after the parameter list, using a colon.
Syntax
function functionName(): returnType {
return value;
}
Example
function getAge(): number {
return 22;
}
console.log("Age:", getAge());
Expected Output
Age: 22
Explanation
-
numberis the declared return type. -
return 22returns a numeric value. -
The returned value is passed to
console.log().
5. Return Types with Different Data Types
TypeScript supports different return types based on the value a function is designed to return.
Example
function getStudentName(): string {
return "Rahul";
}
function getTotalMarks(): number {
return 450;
}
function isPassed(): boolean {
return true;
}
console.log(getStudentName());
console.log(getTotalMarks());
console.log(isPassed());
Expected Output
Rahul
450
true
Explanation
| Return Type | Returned Value |
|---|---|
string |
"Rahul" |
number |
450 |
boolean |
true |
6. Void Return Type
Use void when a function is not intended
to return a meaningful value to its caller.
Example
function displayMessage(): void {
console.log("Function executed successfully.");
}
displayMessage();
Expected Output
Function executed successfully.
Explanation
The function displays a message but does not return a
value for the caller to use. The void
return type expresses this intent.
7. Function with Calculation
Functions can accept input values, perform calculations, and return the calculated result.
Example: Calculate Rectangle Area
function calculateArea(
length: number,
width: number
): number {
return length * width;
}
let area: number = calculateArea(10, 5);
console.log("Rectangle Area:", area);
Expected Output
Rectangle Area: 50
Explanation
The function receives the length and width as numeric parameters. It multiplies them and returns the area as a number.
8. Practical Example: CIIT Student Result
Let's create a function that accepts a student's name and marks, calculates the percentage, and returns it.
Example
function calculatePercentage(
studentName: string,
obtainedMarks: number,
totalMarks: number
): number {
console.log("Student Name:", studentName);
return (obtainedMarks / totalMarks) * 100;
}
let percentage: number =
calculatePercentage("Priya", 420, 500);
console.log("Percentage:", percentage + "%");
Expected Output
Student Name: Priya
Percentage: 84%
Explanation
- The function accepts a student name and two numeric values.
- It calculates the percentage from obtained marks and total marks.
- The calculated percentage is returned as a number.
Common Mistakes
- Passing a value that does not match the parameter type.
- Providing arguments in the wrong order when parameters have different types.
- Returning a value that does not match the declared return type.
- Forgetting to return a result from a function that must produce one.
-
Confusing the function's return value with output
displayed using
console.log().
console.log() displays information, while
return sends a value back to the caller.
They serve different purposes.
Practice Task
Write TypeScript functions to complete the following tasks.
- Create a function that accepts two numbers and returns their difference.
- Create a function that accepts three numbers and returns their average.
- Create a function that accepts a student name and returns a welcome message.
- Create a function that accepts a number and returns whether it is even or odd.
- Create a function that accepts obtained marks and total marks and returns the percentage.
Summary
In this lesson, we learned how to declare typed parameters, pass arguments, and define return types in TypeScript. We also used string, number, boolean, and void return types in examples. These concepts help make functions clearer and improve type checking in our programs.