T

Tipos Avançados

TypeScript Syntax Guide

Union, Interseção, Aliases de Tipo e Tipos Literais

Tipos Avançados

Union, Interseção, Aliases de Tipo e Tipos Literais

TypeScript tipos avançados (typescript)
        
          // Union types
type StringOrNumber = string | number;

function formatValue(value: StringOrNumber): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

// Discriminated unions
interface Square {
  kind: "square";
  size: number;
}

interface Rectangle {
  kind: "rectangle";
  width: number;
  height: number;
}

interface Circle {
  kind: "circle";
  radius: number;
}

type Shape = Square | Rectangle | Circle;

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "square":
      return shape.size ** 2;
    case "rectangle":
      return shape.width * shape.height;
    case "circle":
      return Math.PI * shape.radius ** 2;
  }
}

// Intersection types
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age; // Must have both name and age

const person: Person = {
  name: "John",
  age: 25
};

// Type guards
function isString(value: unknown): value is string {
  return typeof value === "string";
}

function isShape(obj: any): obj is Shape {
  return obj && typeof obj.kind === "string";
}

// Using type guards
function processValue(value: unknown): string {
  if (isString(value)) {
    return value.toUpperCase(); // TypeScript knows value is string
  }
  return "Not a string";
}

// keyof operator
type PersonKeys = keyof Person; // "name" | "age"

// Indexed access types
type PersonName = Person["name"]; // string

// typeof operator for types
const config = {
  apiUrl: "https://api.example.com",
  timeout: 5000
};

type Config = typeof config;

// Mapped types with template literals
type EventHandlers<T extends string> = {
  [K in T as `on${Capitalize<K>}`]: () => void;
};

type ButtonEvents = EventHandlers<'click' | 'hover'>;
// Results in: { onClick: () => void; onHover: () => void; }

// Never type
function throwError(message: string): never {
  throw new Error(message);
}

// Exhaustive checking with never
function assertNever(value: never): never {
  throw new Error(`Unexpected value: ${value}`);
}

function handleShape(shape: Shape) {
  switch (shape.kind) {
    case "square":
      return shape.size;
    case "rectangle":
      return shape.width;
    case "circle":
      return shape.radius;
    default:
      return assertNever(shape); // Ensures all cases are handled
  }
}
        
      

Explanation

TypeScript oferece recursos avançados de tipo como Union Types (um valor pode ser um de vários tipos), Intersection Types (combinando múltiplos tipos em um), Type Aliases (dando um novo nome a um tipo) e Literal Types (restringindo uma variável a valores específicos de string, número ou boolean).

Common Use Cases

  • Criar parâmetros de função flexíveis
  • Combinar interfaces
  • Definir nomes de tipo personalizados para tipos complexos
  • Aplicar valores específicos para variáveis

Related TypeScript Syntax

Master Tipos Avançados in TypeScript

Understanding Tipos Avançados 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 Tipos Avançados effectively in your TypeScript projects.

Key Takeaways

  • Criar parâmetros de função flexíveis
  • Combinar interfaces
  • Definir nomes de tipo personalizados para tipos complexos