Function Types
Functions are the building blocks of TypeScript applications. TypeScript adds type safety to function parameters and return values, catching errors before runtime.
Function Declarations
The most common way to define functions with type annotations:
Click Run to execute your code
Function Expressions
Assign functions to variables with explicit types:
Click Run to execute your code
When to Use Function Expressions
- Callbacks: Passing functions as arguments
- Conditional functions: Assigning different functions based on conditions
- IIFEs: Immediately Invoked Function Expressions
Arrow Functions
Arrow functions provide concise syntax and lexical this binding:
Click Run to execute your code
- Arrow functions don't have their own
this - Cannot be used as constructors
- No
argumentsobject - More concise for simple operations
Return Types
TypeScript can infer return types, but explicit annotations improve clarity and catch errors:
Click Run to execute your code
When to Annotate Return Types
| Scenario | Recommendation |
|---|---|
| Public API functions | Always annotate |
| Complex return types | Always annotate |
| Simple helper functions | Can rely on inference |
| Functions with multiple return paths | Annotate for clarity |
Function Type Aliases
Create reusable function type definitions for consistency:
Click Run to execute your code
Common Mistakes
1. Forgetting Parameter Types
// โ Wrong - parameters have implicit 'any' type
function add(a, b) {
return a + b;
}
// โ Correct - explicit types
function add(a: number, b: number): number {
return a + b;
}
2. Inconsistent Return Types
// โ Wrong - returns different types
function getValue(flag: boolean) {
if (flag) return "yes";
return 0; // string | number - confusing!
}
// โ Correct - consistent return type
function getValue(flag: boolean): string {
return flag ? "yes" : "no";
}
3. Ignoring void Return Type
// โ Wrong - function shouldn't return a value
function logMessage(msg: string): void {
console.log(msg);
return msg; // Error!
}
// โ Correct
function logMessage(msg: string): void {
console.log(msg);
}
Exercise: Calculator Functions
Task: Create a calculator with typed functions!
Click Run to execute your code
Summary
- Always type function parameters - TypeScript cannot infer them
- Return types can be inferred but explicit is better for public APIs
- Arrow functions provide concise syntax and lexical
this - Function type aliases enable reusability and consistency
- void means no return value, never means function never returns
What's Next?
Next, we'll explore Function Parameters including optional, default, and rest parameters!
Enjoying these tutorials?