T

Genéricos

TypeScript Syntax Guide

Criar componentes reutilizáveis que funcionam com uma variedade de tipos

Genéricos

Criar componentes reutilizáveis que funcionam com uma variedade de tipos

TypeScript genéricos (typescript)
        
          // Generic function
function identity<T>(value: T): T {
  return value;
}

// Generic class
class Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }

  peek(): T | undefined {
    return this.items[this.items.length - 1];
  }
}

// Generic constraints
interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(item: T): void {
  console.log(item.length);
}

// Usage
logLength("hello"); // OK
logLength([1, 2, 3]); // OK
// logLength(42); // Error: number has no length property

// Utility types
interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}

// Partial - makes all properties optional
type PartialUser = Partial<User>;

// Pick - select specific properties
type UserCredentials = Pick<User, 'email'>;

// Omit - exclude specific properties
type UserWithoutId = Omit<User, 'id'>;

// Record - create object type with specific key/value types
type UserRoles = Record<string, 'admin' | 'user' | 'moderator'>;

// Mapped types
type ReadonlyUser = {
  readonly [K in keyof User]: User[K];
};

// Conditional types
type IsString<T> = T extends string ? 'yes' : 'no';

type A = IsString<string>;  // 'yes'
type B = IsString<number>;  // 'no'

// Template literal types
type EventName = 'click' | 'hover' | 'focus';
type EventHandler = `on${Capitalize<EventName>}`;

// Utility type examples
const partialUser: PartialUser = { name: "John" };
const credentials: UserCredentials = { email: "john@example.com" };
const roles: UserRoles = {
  "john": "admin",
  "jane": "user"
};
        
      

Explanation

Os genéricos permitem escrever código flexível e reutilizável que funciona com qualquer tipo de dados mantendo a segurança de tipos. Eles permitem que os componentes funcionem sobre uma variedade de tipos em vez de um único.

Common Use Cases

  • Criar estruturas de dados genéricas (ex. arrays, listas)
  • Construir funções reutilizáveis que operam em diferentes tipos
  • Desenvolver bibliotecas type-safe

Related TypeScript Syntax

Master Genéricos in TypeScript

Understanding Genéricos 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 Genéricos effectively in your TypeScript projects.

Key Takeaways

  • Criar estruturas de dados genéricas (ex. arrays, listas)
  • Construir funções reutilizáveis que operam em diferentes tipos
  • Desenvolver bibliotecas type-safe