In Typescript, function parameters allow us to pass values into a function when it is called.
Parameters help define the inputs that a function expects, and we can specify their types to ensure type safety.
function multiple(num1: number, num2: number): number { return num1 * num2; }
We can make parameters optional by adding a "?" after their key-name.
function invoice(message: string, name?: string ): string { if (name) { return `Hi ${name}!, ${message}, `; } else { return `Hello, ${message}!`; } } const result1 = invoice("Thank u for renew subscription") console.log(result1) // Output: "Hello, Thank u for renew subscription!" const result2 = invoice("Thank u for renew subscription", "Alice") console.log(result2) // Output: "Hi Alice!, Thank u for renew subscription, "
function multiply(num1: number, num2: number = 5): number { return num1 * num2; } // passing only one argument const result1 = multiply(10) console.log(result1) // Output: 50 // passing two argument const result2 = multiply(10, 20) console.log(result2) // Output: 200
We can provide default values for parameters.
function sum(...numbers: number[]): number { return numbers.reduce((acc, val) => acc + val, 0); } const result: number = sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); console.log(result) // Output: 55
We can use the rest parameter syntax (...) to represent an indefinite number of parameters as an array.
function printEmployee(name: string, deptNo: number): void { console.log(`Name: ${name}, DepartmentNo: ${deptNo}`); } // Output: "Name: Alice, DepartmentNo: 1002" printEmployee("Alice", 1002 )
function printStatusCodeWithMessage({ code, message }: { code: number, message: string }): void { console.log(`Response: statusCode=${code}, message=${message}`); // Output: "Response: statusCode=200, message=Success" // Output: "Response: statusCode=404, message=Page not found" } printStatusCodeWithMessage({code: 200, message: "Success"}); printStatusCodeWithMessage({code: 404, message: "Page not found"})
We can specify the types of parameters to ensure type safety.
We can use parameter destructuring to simplify the handling of complex objects.