0
0
Typescriptprogramming~5 mins

Why typed functions matter in Typescript

Choose your learning style9 modes available
Introduction

Typed functions help catch mistakes early by clearly showing what kind of information goes in and comes out. This makes your code safer and easier to understand.

When you want to make sure a function only accepts certain types of data, like numbers or strings.
When you want to avoid bugs caused by unexpected data types.
When working with others, so everyone knows what kind of data a function needs and returns.
When building bigger projects where clear rules help keep code organized.
When you want your code editor to help you by showing errors before running the program.
Syntax
Typescript
function functionName(parameter: Type): ReturnType {
  // function body
}

The parameter: Type part tells what type of input the function expects.

The : ReturnType after the parentheses shows what type the function will give back.

Examples
This function takes a string and returns a string.
Typescript
function greet(name: string): string {
  return `Hello, ${name}!`;
}
This function takes two number inputs and returns their sum as a number.
Typescript
function add(a: number, b: number): number {
  return a + b;
}
This function returns true or false depending on whether the number is even.
Typescript
function isEven(num: number): boolean {
  return num % 2 === 0;
}
Sample Program

This program defines a typed function multiply that takes two numbers and returns their product. It then prints the result.

Typescript
function multiply(x: number, y: number): number {
  return x * y;
}

const result = multiply(4, 5);
console.log(`4 times 5 is ${result}`);
OutputSuccess
Important Notes

Typed functions help your editor catch errors before you run your code.

They make your code easier to read and understand for others.

Using types can prevent bugs caused by wrong data types.

Summary

Typed functions clearly show what input and output types are expected.

They help catch mistakes early and make code safer.

Typed functions improve code readability and teamwork.