Why can't I access attributes in union types like this?
export interface ICondition {
field: string
operator: string
value: string
}
export interface IConditionGroup {
conditions: ICondition[]
group_operator: string
}
function foo(item: ICondition | IConditionGroup) {
if(typeof item.conditions === "undefined") { // does not work
let field = item.field; // does not work
///.. do something
} else {
let conditions = item.conditions; // does not work
/// .. do something else
}
}
The errors received are:
error TS2339: Property 'conditions' does not exist on type 'ICondition | IConditionGroup'.
error TS2339: Property 'conditions' does not exist on type 'ICondition | IConditionGroup'.
error TS2339: Property 'field' does not exist on type 'ICondition | IConditionGroup'.
To make it work, casting the types is necessary - like this:
function foo2(inputItem: ICondition | IConditionGroup) {
if(typeof (<IConditionGroup>inputItem).conditions === "undefined") {
let item= (<ICondition>inputItem);
let field = item.field;
///.. do something
} else {
let item= (<IConditionGroup>inputItem);
let conditions = item.conditions;
/// .. do something else
}
}
The need for explicit casting in TypeScript arises from losing type information in JavaScript.