//
In TypeScript, functions are a fundamental part of the language. Just like variables and objects, functions can also have types associated with them. One of the most important aspects of typed functions is type annotations for their parameters. This ensures that the function is called with the correct types of arguments, reducing runtime errors and improving code readability.
TypeScript allows you to specify the expected types of the parameters in a function signature. This is done by placing a colon (:) after each parameter name followed by the type annotation. Here's the basic syntax:
function functionName(param1: Type1, param2: Type2): ReturnType {
// Function body
}
In this syntax:
- `param1` and `param2` are the names of the parameters.
- `Type1` and `Type2` are the types of these parameters.
- `ReturnType` is the type of the value returned by the function.
## Examples
### Basic Example
Let's start with a simple example where we define a function that takes two numbers and returns their sum:
<CodeBlock language="typescript">
{`function add(a: number, b: number): number {
return a + b;
}
const result = add(5, 3);
console.log(result); // Output: 8`}
</CodeBlock>
In this example:
- `a` and `b` are parameters with the type `number`.
- The function returns a value of type `number`.
### Optional Parameters
Sometimes, you might want to make a parameter optional. This can be achieved by adding a question mark (`?`) after the parameter name:
<CodeBlock language="typescript">
{`function greet(name?: string): string {
if (name) {
return \`Hello, \${name}!\`;
}
return 'Hello!';
}
console.log(greet('Alice')); // Output: Hello, Alice!
console.log(greet()); // Output: Hello!`}
</CodeBlock>
In this example:
- `name` is an optional parameter of type `string`.
- If `name` is provided, it returns a personalized greeting; otherwise, it returns a generic greeting.
### Default Parameters
TypeScript also supports default parameters. This allows you to assign a default value to a parameter if no argument is passed:
<CodeBlock language="typescript">
{`function multiply(x: number = 1, y: number = 2): number {
return x * y;
}
console.log(multiply(3, 4)); // Output: 12
console.log(multiply()); // Output: 2
console.log(multiply(5)); // Output: 10`}
</CodeBlock>
In this example:
- `x` and `y` have default values of `1` and `2`, respectively.
- If no arguments are passed, the function uses these defaults.
### Rest Parameters
Rest parameters allow you to represent an indefinite number of arguments as an array. This is useful when you don't know how many arguments a function will receive:
<CodeBlock language="typescript">
{`function sum(...numbers: number[]): number {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5)); // Output: 9
console.log(sum()); // Output: 0`}
</CodeBlock>
In this example:
- `...numbers` is a rest parameter that collects all the arguments into an array of type `number[]`.
- The function calculates the sum of all numbers in the array.
### Destructuring Parameters
TypeScript supports destructuring parameters, which allows you to extract values from objects or arrays directly in the function signature:
<CodeBlock language="typescript">
{`function printUser({ name, age }: { name: string, age: number }): void {
console.log(\`Name: \${name}, Age: \${age}\`);
}
const user = { name: 'Bob', age: 30 };
printUser(user); // Output: Name: Bob, Age: 30`}
</CodeBlock>
In this example:
- The function `printUser` takes an object with `name` and `age` properties.
- The parameters are destructured directly in the function signature.
## What's Next?
Now that you understand how to annotate function parameters in TypeScript, the next step is to learn about <Tip variant="info">Return Types</Tip>. Return types ensure that a function always returns a value of the expected type, enhancing the reliability and predictability of your code.