Reputation: 925
I'm trying to define an object model that contains an object. This object can be of two diferent types of object.
export interface EventParams {
evtType: string;
evtData: FaultOrGoalData| SwapData;
}
export interface FaultOrGoalData {
evtName: string;
player: string;
position: string;
}
export interface SwapData {
swapPlayer: string;
}
My problem here is ts lint telling me that it's impossible to access the data contained in an encapsulated object.
Example: params.evtData.evtName
Hence my question: is it possible to create a union type with interfaces?
Upvotes: 3
Views: 799
Reputation: 249466
Yes you can create a union with interfaces, you just did, but you can only access common members of the union. You can use a type guard to narrow the type and then you can access specific members. In this case you could use an in
type guard:
declare let foo: EventParams;
if('evtName' in foo.evtData) {
foo.evtData.evtName //foo.evtData is of type FaultOrGoalData
}else {
foo.evtData.swapPlayer // foo.evtData is of type SwapData
}
Upvotes: 7