> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript Function

A function in TypeScript is a fundamental execution block that extends standard JavaScript functions by introducing static type annotations for parameters, return values, and execution context. This enforces a strict contract between the caller and the function implementation, allowing the TypeScript compiler to validate inputs and outputs at compile time.

## Basic Typing

TypeScript allows you to explicitly define the types of arguments a function accepts and the type of data it returns. If a return type is omitted, TypeScript will attempt to infer it based on the `return` statements.

```typescript theme={"dark"}
function calculateArea(width: number, height: number): number {
    return width * height;
}

const divide = (a: number, b: number): number => a / b;
```

## Function Types

You can define the signature of a function as a standalone type using a type alias or an interface. This is useful for typing callbacks or enforcing a specific signature on variable declarations.

```typescript theme={"dark"}
type StringTransformer = (input: string) => string;

const toUpperCase: StringTransformer = (text) => text.toUpperCase();
```

## Optional and Default Parameters

By default, TypeScript assumes all defined parameters are required. You can mark a parameter as optional using the `?` postfix, which implicitly adds `undefined` to its type. Alternatively, you can provide a default value, which makes the parameter optional and infers its type from the default assignment.

```typescript theme={"dark"}
// Optional parameter
function buildName(firstName: string, lastName?: string): string {
    return lastName ? `${firstName} ${lastName}` : firstName;
}

// Default parameter
function increment(value: number, step: number = 1): number {
    return value + step;
}
```

## Rest Parameters

When a function needs to accept a variable number of arguments, you use rest parameters. In TypeScript, rest parameters can be typed as an array for an indefinite number of arguments of a specific type, or as a tuple type to enforce a specific sequence and known count of arguments.

```typescript theme={"dark"}
// Array rest parameter
function concatenateStrings(separator: string, ...strings: string[]): string {
    return strings.join(separator);
}

// Tuple rest parameter
function setCoordinates(...args: [number, number, string]): void {
    const [x, y, label] = args;
}
```

## Generic Functions

Generic functions utilize type parameters to handle multiple types while preserving strict type identity between inputs and outputs. Type parameters are declared in angle brackets (`<T>`) immediately preceding the function signature.

When returning intersection types generated via object spread, a type assertion is required because the compiler evaluates the spread as a plain object rather than the specific generic intersection.

```typescript theme={"dark"}
// Single type parameter
function identity<T>(arg: T): T {
    return arg;
}

// Multiple type parameters with constraints and type assertion
function merge<T extends object, U extends object>(target: T, source: U): T & U {
    return { ...target, ...source } as T & U;
}
```

## Function Overloading

TypeScript supports function overloading, allowing you to define multiple call signatures for a single function. The compiler resolves the correct signature based on the arguments provided. The overload signatures are declared first, followed by a single implementation signature that must be compatible with all preceding overloads.

```typescript theme={"dark"}
// Overload signatures
function parseInput(input: string): string[];
function parseInput(input: number): number[];

// Implementation signature
function parseInput(input: string | number): string[] | number[] {
    if (typeof input === "string") {
        return input.split("");
    }
    return [input];
}
```

## `void` and `never` Return Types

TypeScript introduces specific types for functions that do not return standard values:

* **`void`**: Indicates that a function completes execution but does not return a value (or explicitly returns `undefined`).
* **`never`**: Indicates that a function will *never* successfully complete execution, typically because it throws an error or contains an infinite loop.

```typescript theme={"dark"}
function logWarning(message: string): void {
    console.warn(message);
}

function terminateProcess(reason: string): never {
    throw new Error(`Process terminated: ${reason}`);
}
```

## `this` Typing

In TypeScript, you can explicitly type the `this` context of a function to prevent runtime errors caused by unbound execution contexts. The `this` parameter is a pseudo-parameter that must appear first in the parameter list and is erased during compilation.

```typescript theme={"dark"}
interface User {
    name: string;
    greet(this: User): void;
}

const user: User = {
    name: "Alice",
    greet(this: User) {
        console.log(`Hello, ${this.name}`);
    }
};
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor TypeScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
