Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!