TypeScript enhances JavaScript functions by adding explicit parameter type annotations, return type annotations, optional/default parameters, function types, and function overloading.
param: type: Standard parameter.param?: type: Optional parameter.param: type = defaultValue: Default parameter....restParam: type[]: Rest parameter array.// Standard function signature with explicit return type
function calculateTotal(price: number, taxRate: number = 0.05, discount?: number): number {
const finalDiscount = discount ?? 0;
const subtotal = price - finalDiscount;
return subtotal + subtotal * taxRate;
}
// Function Type Signature Alias
type MathOperation = (a: number, b: number) => number;
const add: MathOperation = (x, y) => x + y;
const multiply: MathOperation = (x, y) => x * y;
// Function Overloads Signature Definitions
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
// Function Implementation
function combine(a: any, b: any): any {
return a + b;
}
const strResult = combine("Hello, ", "TypeScript"); // Type: string
const numResult = combine(50, 100); // Type: number
console.log(`Subtotal: ${calculateTotal(100, 0.1, 10)} | Combined: ${strResult}`);
Define a function type StringFormatter = (input: string) => string. Implement a function uppercaseFormatter matching this signature.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With