> ## 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 building block that encapsulates reusable logic, distinguished from standard JavaScript by the addition of static typing for parameters, return values, and execution context (`this`). TypeScript enforces strict type checking during compilation to ensure that function invocations strictly adhere to their defined structural signatures.

## Parameter and Return Type Annotations

TypeScript allows explicit type declarations for both the arguments a function accepts and the value it returns. If a return type is omitted, TypeScript will attempt to infer it based on the `return` statements.

```typescript theme={"dark"}
// Named function with explicit parameter and return types
function calculateArea(width: number, height: number): number {
    return width * height;
}

// Arrow function with explicit types
const concatenate = (str1: string, str2: string): string => `${str1}${str2}`;
```

## Function Types

Function signatures can be abstracted into standalone types or interfaces. This enables contextual typing, where TypeScript infers the types of the parameters and return value based on the assigned type alias.

```typescript theme={"dark"}
// Defining a function type alias
type StringTransformer = (input: string) => string;

// The compiler infers 'text' is a string and the return is a string
const toUpperCase: StringTransformer = (text) => text.toUpperCase();
```

## Optional and Default Parameters

By default, TypeScript assumes all parameters defined in a function signature are required.

* **Optional Parameters:** Denoted by a `?` postfix on the parameter identifier. They must appear after all required parameters.
* **Default Parameters:** Assigned using the `=` operator. TypeScript infers the parameter type from the default value if no explicit type annotation is provided.

```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

To represent an unbounded number of arguments, TypeScript uses rest parameters. The rest parameter must be the final parameter in the signature and is typed as an array.

```typescript theme={"dark"}
function sumAll(initialValue: number, ...additionalValues: number[]): number {
    return additionalValues.reduce((acc, val) => acc + val, initialValue);
}
```

## Function Overloading

TypeScript supports function overloading, allowing multiple type signatures for a single function implementation. The compiler resolves the call against the list of overload signatures, evaluating them from top to bottom. The actual implementation signature must be broad enough to encompass all overload signatures and is not directly callable itself.

```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];
}
```

## Special Return Types: `void` and `never`

TypeScript introduces specific types to represent the absence of a return value or the impossibility of returning.

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

```typescript theme={"dark"}
function logEvent(event: string): void {
    console.log(`Event: ${event}`);
}

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

## Typing the `this` Context

In JavaScript, the value of `this` is determined by how a function is called. TypeScript allows you to explicitly type the `this` context by declaring it as a pseudo-parameter. It must be the first parameter in the function signature and is stripped out during compilation.

```typescript theme={"dark"}
interface Handler {
    elementId: string;
    onClick(this: Handler, event: Event): void;
}

const myHandler: Handler = {
    elementId: "btn-submit",
    onClick(this: Handler, event: Event) {
        console.log(`Clicked ${this.elementId}`);
    }
};
```

<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>
