Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript union type with various interfaces

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?

like image 805
Florent Arlandis Avatar asked May 05 '26 03:05

Florent Arlandis


1 Answers

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
}
like image 95
Titian Cernicova-Dragomir Avatar answered May 06 '26 18:05

Titian Cernicova-Dragomir