Function Declaration: A named function defined using the function keyword, with explicit parameter and return types.
function functionName(param: type): returnType {
// body
}
Function Expression: An anonymous function assigned to a variable, with types for parameters and return value.
const functionName: (param: type) => returnType = function(param) {
// body
};
Types in Functions: TypeScript enforces parameter and return types at compile time, catching type errors before runtime.
Use Case: Ensuring type safety for calculations, API calls, or data processing.
// Function Declaration
function add(a: number, b: number): number {
return a + b;
}
// Function Expression
const multiply: (x: number, y: number) => number = function(x, y) {
return x * y;
};
// Usage
console.log(add(5, 3)); // Output: 8
console.log(multiply(4, 2)); // Output: 8
Note:
add is a declaration with typed parameters (number) and return type (number).multiply is an expression with a function type annotation.a, b, x, y are numbers and the return value is a number.Optional Parameters: Parameters that can be omitted, marked with ?. Must come after required parameters.
param?: type.Default Parameters: Parameters with a default value, used if no value or undefined is passed.
param: type = defaultValue.Type Safety: TypeScript enforces types for optional/default parameters and checks for undefined in optional cases.
Use Case: Flexible function signatures for varying input scenarios.
// Optional and Default Parameters
function greet(name: string, greeting?: string, prefix: string = "Mr."): string {
const message = greeting || "Hello";
return `${message}, ${prefix} ${name}!`;
}
// Usage
console.log(greet("kristal")); // Output: Hello, Mr. kristal!
console.log(greet("Sashi", "Hi")); // Output: Hi, Mr. Sashi!
console.log(greet("hari", "Hey", "Dr.")); // Output: Hey, Dr. hari!
Rest Parameters: Allow a function to accept a variable number of arguments as an array, using the ... syntax.
...param: type[].Type Safety: TypeScript enforces that rest parameters are an array of a specific type.
Use Case: Handling dynamic numbers of inputs (e.g., summing numbers, logging messages).
// Rest Parameters
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
// Usage
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(10)); // Output: 10
console.log(sum()); // Output: 0
Function Types: Define the signature of a function, specifying parameter types and return type.
(param: type) => returnType.Type Aliases: Named types created with the type keyword, often used for function signatures or complex types.
type AliasName = (param: type) => returnType.Use Case: Reusing function signatures, ensuring consistent function types across variables or parameters.
// Function Types and Type Aliases
type MathOperation = (x: number, y: number) => number;
// Function using type alias
const add: MathOperation = (x, y) => x + y;
const subtract: MathOperation = (x, y) => x - y;
// Function accepting a function type
function applyOperation(x: number, y: number, operation: MathOperation): number {
return operation(x, y);
}
// Usage
console.log(applyOperation(5, 3, add)); // Output: 8
console.log(applyOperation(5, 3, subtract)); // Output: 2
Project Structure:
ts-functions/
├── src/
│ └── main.ts
├── tsconfig.json
└── package.json
main.ts:
// Comprehensive TypeScript Functions Example
type Logger = (message: string, level?: string) => string;
// Function Declaration with Optional Parameter
function logMessage(message: string, level?: string): string {
return `[${level || "INFO"}] ${message}`;
}
// Function Expression with Default Parameter
const processData: (data: number[], prefix: string) => string = function(
data,
prefix = "Data:"
) {
return `${prefix} ${data.join(", ")}`;
};
// Rest Parameters
function average(...numbers: number[]): number {
if (numbers.length === 0) return 0;
return numbers.reduce((sum, num) => sum + num, 0) / numbers.length;
}
// Type Alias for Operation
type Operation = (a: number, b: number) => number;
// Function using Type Alias
function executeOperation(a: number, b: number, op: Operation): number {
return op(a, b);
}
// Example Usage
const multiply: Operation = (a, b) => a * b;
console.log(logMessage("System started")); // Output: [INFO] System started
console.log(logMessage("Error occurred", "ERROR")); // Output: [ERROR] Error occurred
console.log(processData([1, 2, 3])); // Output: Data: 1, 2, 3
console.log(processData([4, 5, 6], "Values:")); // Output: Values: 4, 5, 6
console.log(average(10, 20, 30)); // Output: 20
console.log(executeOperation(5, 3, multiply)); // Output: 15
package.json:
{
"name": "ts-functions",
"version": "1.0.0",
"scripts": {
"start": "tsc && node dist/main.js",
"build": "tsc",
"watch": "tsc --watch"
},
"devDependencies": {
"typescript": "^5.6.2"
}
}
tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
Steps to Run:
npm install.npm run build.npm start.Output:
[INFO] System started
[ERROR] Error occurred
Data: 1, 2, 3
Values: 4, 5, 6
20
15
Description:
logMessage uses optional parameter level.processData uses a default parameter prefix.average handles variable numbers of inputs.Operation ensures consistent function signatures for executeOperation.undefined for optional parameters.undefined for optional parameters.type[] for clarity.void for functions with no return value.undefined, invalid types).tsconfig.json with strict settings (e.g., "strict": true) for robust type checking.