TS Functions
Functions in TypeScript allow you to define reusable blocks of code with strict type checking. They can have parameter types, return types, and optional or default parameters.
Key Topics
Function Syntax
TypeScript functions are defined with parameter types and return types for improved type safety.
function add(a: number, b: number): number {
return a + b;
}
console.log(add(5, 10)); // 15
Output
15
Explanation: The add
function takes two number
parameters and returns a number
. The return type is explicitly defined.
Optional Parameters
Parameters can be marked as optional using the ?
operator. Optional parameters must appear after required parameters.
function greet(name: string, message?: string): string {
return message ? `${message}, ${name}!` : `Hello, ${name}!`;
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Bob", "Hi")); // Hi, Bob!
Output
Hello, Alice!
Hi, Bob!
Explanation: The message
parameter is optional. When not provided, the function defaults to a basic greeting.
Default Parameters
Default parameter values can be provided, ensuring the function works even if arguments are not explicitly passed.
function multiply(a: number, b: number = 1): number {
return a * b;
}
console.log(multiply(5)); // 5
console.log(multiply(5, 3)); // 15
Output
5
15
Explanation: The b
parameter has a default value of 1
, which is used when the second argument is not provided.
Specifying Return Types
You can explicitly define the return type of a function to ensure it matches the expected type.
function isEven(num: number): boolean {
return num % 2 === 0;
}
console.log(isEven(4)); // true
console.log(isEven(7)); // false
Output
true
false
Explanation: The isEven
function returns a boolean
based on whether the input num
is even or odd.
Key Takeaways
- Parameter Types: TypeScript enforces types for function parameters to catch errors at compile time.
- Optional Parameters: Use
?
to define parameters that may not always be provided. - Default Parameters: Provide default values to ensure functions work even when arguments are missing.
- Return Types: Explicitly define return types for predictable and type-safe functions.