Skip to main content

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.

A function expression in TypeScript defines a function as part of a larger expression syntax, typically by assigning an anonymous or named function to a variable. TypeScript enhances standard JavaScript function expressions by enforcing strict static typing on parameters, return values, and the overall function signature. Unlike function declarations, function expressions are not hoisted; they are evaluated at runtime when the execution thread reaches the assignment.

Syntax Visualization

Function expressions can be written using the function keyword or as arrow functions. TypeScript allows you to annotate the parameters and the return type directly within the expression.
// Standard function expression with inline type annotations
const add = function(x: number, y: number): number {
    return x + y;
};

// Arrow function expression with inline type annotations
const subtract = (x: number, y: number): number => {
    return x - y;
};

Function Type Expressions (Variable Typing)

In TypeScript, you can decouple the type signature from the function implementation by explicitly typing the variable that holds the function expression. The syntax for a function type expression uses an arrow => to separate the parameter list from the return type.
// Variable explicitly typed with a function type signature
const multiply: (a: number, b: number) => number = function(x, y) {
    return x * y;
};

Contextual Typing (Type Inference)

When a function expression is assigned to a variable that already has a declared function type, TypeScript applies contextual typing. The TypeScript compiler infers the types of the parameters and the return value of the function expression based on the variable’s type signature, making inline annotations redundant.
type MathOperation = (a: number, b: number) => number;

// Parameter types (x, y) and return type are inferred from MathOperation
const divide: MathOperation = (x, y) => {
    return x / y; 
};

Named Function Expressions

While function expressions are typically anonymous, they can be assigned an internal identifier. This name is local only to the function body itself and is strictly used for internal recursion or identifying the function within stack traces.
const calculateFactorial = function factorial(n: number): number {
    if (n <= 1) return 1;
    // 'factorial' is accessible here, but not outside the expression
    return n * factorial(n - 1); 
};
Master TypeScript with Deep Grasping Methodology!Learn More