Reputation: 505
Please consider the simple union type example below:
interface Alarm {
alarmText: string,
quali: number
}
interface Car {
speed: number
}
type unionT = Alarm | Car;
var alarm: Alarm = {
alarmText: "ALARM!!!",
quali: 42
};
var bar: unionT = alarm;
bar.alarmText // ERROR
When the type unionT consist of different interfaces like Alarm
and Car
I cannot access the alarmText
property anymore. The way I understand it is that the compiler cannot infer that I am referring to the alarm object. Only non-disjoint properties can be accessed in union types. Right?
If this is correct, how can I ever get my original alarm object back once it is declared in a variable of the union type? I first though that I could do a type guard like
if (typeof bar === 'Alarm') {
bar.alarmText
}
But typeof bar
is just 'object'
and thus the gaurd does not make any sense.
Anyone?
Upvotes: 3
Views: 482
Reputation: 250882
You can write a custom type guard to achieve this:
function isAlarm(a: Alarm | Car): a is Alarm {
// Some check to see if this is an Alarm
return (<Object>a).hasOwnProperty('alarmText');
}
if (isAlarm(bar)) {
bar.alarmText;
}
Upvotes: 1