TypeScript Functions

Functions help us organize and reuse code. In TypeScript, functions work just like in JavaScript, but you can also describe what kind of values go in and what should come out. This makes your code easier to understand and helps catch mistakes before they happen.

Writing Functions in TypeScript

A basic function in TypeScript looks like this:

typescript
1
2
3
          function greet(name: string) {
  console.log("Hello, " + name);
}
        

You define the name of the function, the parameter(s), and what the function does. TypeScript makes sure you're passing the right kind of values.

You can also return values:

typescript
1
2
3
          function add(a: number, b: number): number {
  return a + b;
}
        

Here, a and b must be numbers, and the function must return a number.

Function Types: Parameters and Return Types

In TypeScript, every function can have a type signature. This includes the types of its parameters and the return type. This helps avoid errors like sending the wrong kind of value to a function.

Example:

typescript
1
2
3
          function isEven(num: number): boolean {
  return num % 2 === 0;
}
        

If you try to pass a string to isEven, TypeScript will show an error before you even run the code.

You can also write function types separately and use them to describe variables that store functions:

typescript
1
2
          let multiply: (x: number, y: number) => number;
multiply = (x, y) => x * y;
        

Optional and Default Parameters

Sometimes, a parameter may not be required. You can mark it as optional using ?:

typescript
1
2
3
4
5
6
7
          function greet(name?: string) {
  if (name) {
    console.log("Hello, " + name);
  } else {
    console.log("Hello!");
  }
}
        

Or you can give it a default value:

typescript
1
2
3
          function greet(name: string = "Guest") {
  console.log("Hello, " + name);
}
        

This makes your functions flexible and easier to use in different situations. Optional and default parameters are simple but powerful tools that improve the usability of your code.