3

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?

3
  • 2
    Can you include the actual code that breaks? If you're just blithely trying to use params.evtData.evtName without checking if params.evtData is a FaultOrGoalData first, that's the sort of error TypeScript is designed to catch. If you are checking, and TypeScript is still reporting an error, then it might not be one of the checks the compiler understands. As it stands, the answer to your question is: "yes it is possible, and the error you're getting is a good one". Commented Jun 20, 2018 at 13:12
  • it is an error I'm getting with tslint before runtime. So I believe at this point it doesn't matter what's actually in the object Commented Jun 20, 2018 at 13:17
  • Yes, TypeScript compiler errors happen before runtime, but they warn about problems you expect to see at runtime. In this case, the error is saying "I don't know that params.evtData is going to have an evtName member, so I'm complaining about it now." @TitianCernicova-Dragomir's answer is one way to deal with the error. Commented Jun 20, 2018 at 13:22

1 Answer 1

7

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.