T
Typed Functions
TypeScript syntax guide
Function typing and overloads in TypeScript
Typed Functions
Function typing and overloads in TypeScript
TypeScript typed functions (typescript)
// Function type annotation
function greet(name: string): string {
return `Hello, ${name}!`;
}
// Arrow function with types
const greetArrow = (name: string): string => `Hello, ${name}!`;
// Optional parameters
function createUser(name: string, age?: number): User {
return {
id: Math.random(),
name,
createdAt: new Date(),
...(age && { age })
};
}
// Default parameters
function multiply(a: number, b: number = 2): number {
return a * b;
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
// Function overloads
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}
// Generic functions
function identity<T>(value: T): T {
return value;
}
function mapArray<T, U>(arr: T[], mapper: (item: T) => U): U[] {
return arr.map(mapper);
}
// Usage
const result1 = identity<string>("hello");
const result2 = identity(42);
const numbers = [1, 2, 3];
const strings = mapArray(numbers, n => n.toString());
Explanation
TypeScript allows typing function parameters and return values. Function overloads provide multiple call signatures, while generics enable reusable type-safe functions.
Common Use Cases
- Type-safe APIs
- Better documentation
- Compile-time error checking
- IntelliSense support
Related TypeScript Syntax
Master Typed Functions in TypeScript
Understanding typed functions is fundamental to writing clean and efficient TypeScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using typed functions effectively in your TypeScript projects.
Key Takeaways
- Type-safe APIs
- Better documentation
- Compile-time error checking