Home > Back-end >  Why isn't typescript recognizing my type extensions?
Why isn't typescript recognizing my type extensions?

Time:07-11

Typescript should be able to tell which extension of a type you are dealing with based on its properties using switch case.

Here are my types:

export enum MessageType {
    CallEnd = "CallEnd",
    L2Measurement = "L2Measurement",
}

export type TraceMessages = {
    messageType: MessageType;
};

export interface TraceMessageL2Measurement extends TraceMessages {
    messageType: MessageType.L2Measurement;
    l2Measurement: L2MeasurementMessage;
}

export interface TraceMessageCallEnd extends TraceMessages {
    messageType: MessageType.CallEnd;
    callEnd: CallEndMessage;
}

export type TraceMessage =
    | TraceMessages
    | TraceMessageCallEnd
    | TraceMessageL2Measurement;

Now, with a switch case structure like:

switch (l2message.messageType) {
    case MessageType.L2Measurement:
        // Typescript should now know that l2message: TraceMessageL2Measurement

But Typescript does not understand this, and only offers the base type's (TraceMessages') properties. What am I doing wrong?

Thanks!

CodePudding user response:

You just have to exclude TraceMessages from definition of TraceMessage:

export type TraceMessage =
  | TraceMessageCallEnd
  | TraceMessageL2Measurement;

Otherwise TypeScript can't get rid of the possibility of l2message being a TraceMessage with messageType: "L2Measurement", which do not have the l2Measurement property.

  • Related