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

184
Visualizações
Determining type based on it's props

I have these two types:

export type Equipment = {
  id: string;
  name: string;
  path: WorkCenter[];
  key?: string;
  pathToElement?: string[];
  machine_id?: StatesData.MachineMapping['machine_id'];
  machine_codes?: StatesData.MachineMapping['machine_codes'];
  timeout_s?: StatesData.MachineMapping['timeout_s'];
  stateMachines?: StatesData.MachineState['machines'];
};

export type WorkCenter = {
  id: string;
  name: string;
  children?: Equipment[];
  key?: string;
  pathToElement?: string[];
  stateMachines?: StatesData.MachineState['machines'];
};

At one point in my code, I get a variable that can either be of type Equipment, or WorkCenter.

How can I determine which it is? Depending on whether it's Equipment or WorkCenter, I need different logic to happen.

So far I am accepting this:

args: Equipment | WorkCenter

But can't think of a simple way to test which type this is.

Doing typeof would make most sense, but it's doesn't work for ts types, so won't work. I also can't just test for a property existing only on Equipment, since ts will see it as not a union. What am I missing?

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

0

I also can't just test for a property existing only on Equipment, since ts will see it as not a union.

Using square bracket notation allows you to test without TS complaining

type TypeOne = {
  path: string;
};

type TypeTwo = {
  child: string;
};

const testIt = (t: TypeOne | TypeTwo) => {
  console.log(t['child']);
}
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