T
Funções Tipadas
TypeScript Syntax Guide
Tipagem de funções e sobrecargas em TypeScript
Funções Tipadas
Tipagem de funções e sobrecargas em TypeScript
TypeScript funções tipadas (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 permite tipar parâmetros de função e valores de retorno. Sobrecargas de função fornecem múltiplas assinaturas de chamada, enquanto genéricos permitem funções reutilizáveis e type-safe.
Common Use Cases
- APIs type-safe
- Melhor documentação
- Verificação de erros em tempo de compilação
- Suporte IntelliSense
Related TypeScript Syntax
Master Funções Tipadas in TypeScript
Understanding Funções Tipadas 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 Funções Tipadas effectively in your TypeScript projects.
Key Takeaways
- APIs type-safe
- Melhor documentação
- Verificação de erros em tempo de compilação