Functions

TS Functions

Defining TypeScript Functions

TypeScript functions use typed parameters and return types with overloads.

Introduction to TypeScript Functions

TypeScript functions are a core feature of the language, offering strong typing capabilities, including typed parameters, return types, and function overloads. This ensures that your code is more predictable and easier to debug.

Defining Functions with Typed Parameters

In TypeScript, you can define functions with typed parameters. This enforces the types of arguments that the function can accept, allowing for better error checking and IntelliSense support in most IDEs.

Here's a basic example of a function with typed parameters:

In the above example, the add function takes two parameters, a and b, both of which are numbers. The function returns a number, ensuring that only numbers are used in the addition operation.

Function Return Types

TypeScript also allows you to specify the return type of a function. This helps you understand what type of value a function will produce and can prevent unintended type errors.

Consider the following example:

Here, the greet function is expected to return a string. If the implementation of the function attempted to return a different type, TypeScript would flag it as an error.

Overloading Functions

Function overloading in TypeScript allows you to define multiple signatures for a function. This is useful when you want a function to handle different types of parameters or return different types based on the input.

Here's an example of function overloading:

In this example, the getValue function has two overloads: one that accepts a number and another that accepts a string. The actual implementation of getValue can handle any type, but TypeScript ensures that the function is used with the appropriate types as defined in the overloads.

Practical Example of Using Functions in TypeScript

Let's put these concepts together in a practical example. Consider a function that calculates the area of different shapes:

In this example, the calculateArea function accepts a Shape type and a variable number of numeric values. It calculates the area based on the shape type, demonstrating the use of typed parameters, return types, and even the rest parameter syntax.