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?
CodePudding user response:
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']);
}