Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
Make the type of one property depending upon other properties

Basically a function can take either of these two types or param:

{a: string, b: number, c: SomeType} {a: string, b: number, d: SomeOtherType}

I know I can write the type of the parameter as {a: string, b: number, c: SomeType} | {a: string, b: number, d: SomeOtherType}, but I'm trying to come up with something like:

{a: string, b: number} & ({c: SomeType} | {d: SomeOtherType})

So that I don't have to repeat the first two properties, is this possible?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can define a type alias for the static properties and then use the intersection operator (&) to combine them with the optional union like this:

TS Playground

type StaticOptions = {
  a: string;
  b: number;
};

type Options = StaticOptions & (
  { c: boolean } | { d: null }
);

function fn (options: Options): void {}


Update in response to your comment:

You can define the exclusive properties as optional and never in each other's shape for "easier" DX:

TS Playground

type StaticOptions = {
  a: string;
  b: number;
};

type Options = StaticOptions & (
  {
    c: boolean;
    d?: never;
  }
  | {
    c?: never;
    d: null;
  }
);

function fn (options: Options): void {
  const {
    a, // string
    b, // number
    c, // boolean | undefined
    d, // null | undefined
  } = options;
}

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda