TypeScript Functions
A TypeScript function is a reusable block of code that can accept typed parameters, perform an operation, and return a typed result. Type annotations help the compiler detect invalid arguments and incompatible return values before the JavaScript runs.
TypeScript supports function declarations, function expressions, arrow functions, callbacks, overloads, generic functions, optional parameters, default parameters, and rest parameters. The generated JavaScript contains ordinary JavaScript functions because TypeScript types are removed during compilation.
TypeScript Function Declaration and Definition
A named function has two practical parts:
- Function declaration: Identifies the function and describes its parameters and return type.
- Function body: Contains the statements that run whenever the function is called.
TypeScript Function Syntax
The following syntax declares a named function. Parameter types appear after the parameter names, while the return type appears after the closing parenthesis.
function function_name (parameter1[:type], parameter2[:type]) [:return_type] {
// set of statements
// that form the function body
}
- function is the keyword used to declare a named function.
- function_name is the identifier used to reference or call the function.
- parameters are comma-separated inputs. A parameter can have an explicit type annotation.
- return_type describes the type of value returned. TypeScript can often infer it from the return statements, but an explicit annotation documents the contract and checks the implementation.
Calling a TypeScript Function
Call a function by writing its name followed by parentheses. Values supplied in the call are arguments, while the variables declared in the function signature are parameters. TypeScript checks the number and types of arguments against the signature.
Example: Function with Number Parameters and Return Type
The following function accepts two numbers and returns their sum. The parameter types and return type are explicitly declared. The function is then called with the arguments 10 and 12.
example.ts
function sum(a:number, b:number) :number {
var result:number = a+b
return result
}
var c:number = sum(10, 12)
console.log(c)
Output
22
After compilation, the type annotations are removed. The resulting JavaScript retains the function logic:
example.js
function sum(a, b) {
var result = a + b;
return result;
}
var c = sum(10, 12);
console.log(c);
Function Declarations, Expressions, and Arrow Functions
The same operation can be represented with several TypeScript function syntaxes. A declaration introduces a named function, an expression stores a function in a variable, and an arrow function provides a compact expression-oriented form.
// Function declaration
function multiply(a: number, b: number): number {
return a * b;
}
// Function expression
const subtract = function (a: number, b: number): number {
return a - b;
};
// Arrow function
const divide = (a: number, b: number): number => a / b;
console.log(multiply(4, 3));
console.log(subtract(10, 6));
console.log(divide(20, 5));
An arrow function with a single expression returns that expression implicitly. Use braces and an explicit return statement when its body contains multiple statements.
TypeScript Function Types
A function type describes the parameters and return value of a callable value. It is useful for variables, callbacks, object properties, and parameters that receive functions.
type Operation = (left: number, right: number) => number;
The parameter names in a function type are descriptive. Compatibility is determined by their positions and types, not by the names used in the implementation.
type Operation = (left: number, right: number) => number;
const add: Operation = (a, b) => a + b;
const multiplyValues: Operation = (x, y) => x * y;
console.log(add(5, 7));
console.log(multiplyValues(5, 7));
TypeScript Function Return Types
TypeScript can infer a function’s return type, but an explicit annotation is useful for public APIs and functions whose intended result should remain stable. Use void when callers should not use a returned value. Use never when a function cannot complete normally, such as one that always throws an error.
function logMessage(message: string): void {
console.log(message);
}
function fail(message: string): never {
throw new Error(message);
}
Default Parameter Values in TypeScript Functions
A default value is used when the corresponding argument is omitted or explicitly passed as undefined. Parameters with default values are commonly placed after required parameters so function calls remain easy to read.
The following example applies 2 as the value of b when the second argument is omitted.
TypeScript Default Parameter Example
example.ts
function sum(a, b=2) {
return a+b
}
sum(10,12) // a=10, b=22, result = 10 + 22 = 22
sum(10) // a=10, b=2, result = 10 + 2 = 12
The first call supplies both arguments and evaluates to 22. The second call omits b, so its default value is used and the result is 12.
Rest Parameters in TypeScript Functions
A rest parameter collects zero or more remaining arguments into an array. It is declared with three dots and must be the last parameter in the function signature. Its array type determines which values callers may supply.
TypeScript Rest Parameter Example
The following sum function accepts any number of numeric arguments.
example.ts
function sum(...values:number[]) :number {
var result:number = 0
for(var i in values)
result += values[i]
return result
}
sum(41,52,6,1,85,32)
Output
217
When the function is compiled to JavaScript, the compiler emits code that gathers the arguments into an array:
example.js
function sum() {
var values = [];
for (var _i = 0; _i < arguments.length; _i++) {
values[_i] = arguments[_i];
}
var result = 0;
for (var i in values)
result += values[i];
return result;
}
sum(41, 52, 6, 1, 85, 32);
Optional Parameters in TypeScript Functions
Add a question mark after a parameter name to make that parameter optional. An omitted optional parameter has the value undefined, so the function body must handle that possibility. Optional parameters should normally appear after required parameters.
Optional Parameter Example and Undefined Handling
In the following original example, a and b are required while c is optional.
example.ts
function sum(a,b,c?) :number {
// a and b are mandatory
// c is optional
return a+b+c
}
sum(41,52) // returns 93
sum(41,52,6) // returns 99
Compiled JavaScript code is given below.
example.js
function sum(a, b, c) {
// a and b are mandatory
// c is optional
return a + b + c;
}
sum(41, 52); // returns 93
sum(41, 52, 6); // returns 99
There is an important issue in that example: when c is omitted, its runtime value is undefined. Adding a number to undefined produces NaN, not 93. Handle the missing value explicitly or give the parameter a default value.
function safeSum(a: number, b: number, c?: number): number {
return a + b + (c ?? 0);
}
console.log(safeSum(41, 52));
console.log(safeSum(41, 52, 6));
Output
93
99
Callbacks as TypeScript Function Parameters
A callback is a function passed to another function. Give the callback its own function type so TypeScript can check both the accepted arguments and the returned value.
function transform(
value: number,
operation: (input: number) => number
): number {
return operation(value);
}
const doubled = transform(6, value => value * 2);
console.log(doubled);
TypeScript Function Overloads
Function overloads describe multiple supported call signatures for one implementation. Write the public overload signatures first, followed by a single implementation signature broad enough to handle every declared form.
function formatValue(value: number): string;
function formatValue(value: Date): string;
function formatValue(value: number | Date): string {
if (value instanceof Date) {
return value.toISOString();
}
return value.toFixed(2);
}
console.log(formatValue(12.5));
console.log(formatValue(new Date("2026-01-15T00:00:00Z")));
Callers see the overload signatures rather than the implementation signature. Use a union parameter instead when every operation is valid for the same union type and separate call signatures add no useful distinction.
Generic Functions in TypeScript
A generic function preserves a relationship between its input and output types. The following identity function returns the same type that it receives without using the unsafe any type.
function identity<T>(value: T): T {
return value;
}
const text = identity("TypeScript");
const count = identity(25);
TypeScript infers string for text and number for count. Explicit type arguments are usually unnecessary when the compiler can infer them from the supplied arguments.
Common TypeScript Function Errors
- Ignoring an optional parameter: An omitted parameter is
undefined; narrow it, use nullish coalescing, or provide a default. - Using
anyunnecessarily: Prefer a specific type, union,unknown, or generic type parameter. - Returning an inconsistent type: Add an explicit return annotation when a stable function contract is required.
- Placing an optional parameter before a required parameter: Put required parameters first unless the API specifically requires callers to pass
undefined. - Confusing rest parameters with arrays: A rest parameter collects separate arguments, while an array parameter expects one array argument.
- Adding overloads without distinct call behavior: Prefer a union parameter when one signature accurately represents every valid call.
TypeScript Functions FAQ
What are functions in TypeScript?
Functions are callable blocks of JavaScript logic enhanced with TypeScript type checking. Their signatures can specify parameter types, optional or default parameters, rest parameters, and return types.
What is a TypeScript function type?
A function type defines the inputs and output of a callable value, such as (value: number) => string. It can be assigned to a type alias and reused for callbacks, variables, and object properties.
Does a TypeScript function need an explicit return type?
No. TypeScript can usually infer the return type from the implementation. An explicit return type is still useful for documenting a public contract and detecting unintended changes to the returned value.
What is the difference between an optional and a default parameter?
An optional parameter may be omitted and is then undefined. A default parameter uses its declared default when the argument is omitted or passed as undefined.
How do you type a TypeScript arrow function?
Add annotations to its parameters and place the return type after the parameter list, as in (a: number, b: number): number => a + b. You can also assign the arrow function to a variable with a reusable function type.
TypeScript Function Tutorial Review Checklist
- Confirm that each parameter has an intentional type and required, optional, default, or rest behavior.
- Verify that optional parameters are handled when their runtime value is
undefined. - Check that documented function results match the actual JavaScript output.
- Use an explicit return type for exported functions when it clarifies or protects the API contract.
- Confirm that callback types describe both their arguments and return values.
- Use overloads only when the function genuinely supports distinct call signatures.
- Compile the examples with the project’s current TypeScript configuration before publishing them.
Summary of TypeScript Function Features
TypeScript functions combine JavaScript function behavior with compile-time checks for parameters and return values. Named declarations, function expressions, and arrow functions cover the common syntax forms. Function types describe callbacks and callable variables, while default, optional, and rest parameters support different input patterns. Overloads and generics provide additional type safety for functions with more flexible APIs.
Continue with the TypeScript Tutorial for related TypeScript concepts and examples.
TutorialKart.com