Typescritp: Sobrecarga de Construtor

작성자

카테고리:

← 피드로
DEV Community · Yuri Peixinho · 2026-06-14 개발(SW)

Yuri Peixinho

Introdução

Assim como funções, construtores podem ter múltiplas assinaturas:

O problema

class Evento {
  constructor(id: string, tipo: string, competencia: string) { ... }
  // como aceitar também só id e tipo, sem competencia?
}

Enter fullscreen mode Exit fullscreen mode

Solução — overload signatures

class Evento {
  id: string;
  tipo: string;
  competencia: string;

  // assinaturas
  constructor(id: string, tipo: string);
  constructor(id: string, tipo: string, competencia: string);

  // implementação
  constructor(id: string, tipo: string, competencia: string = "nao-definida") {
    this.id = id;
    this.tipo = tipo;
    this.competencia = competencia;
  }
}

new Evento("1", "R-2010");              // ✅ primeira assinatura
new Evento("1", "R-2010", "2024-01");   // ✅ segunda assinatura

Enter fullscreen mode Exit fullscreen mode

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다