'mix default interface with two additional interfaces

I just want to extend an "Error interface" with two additional options.

typescript playground: https://tsplay.dev/Nr5Mlw

  1. interface Error is an common interface describing default Error
  2. interface RequestError and interface InvariantError just extending common interface

issue: the Response Error interface has to be a mix of that three interfaces

interface Error {
  error: {
    message?: string,
    name: "InvariantError" | "RequestError" | string,
  };
}

interface InvariantError extends Error {
  error: {
    message: string,
    name: "InvariantError",
  };
}

interface RequestError extends Error {
  error: {
    name: "RequestError",
    response: {
      message?: string,
    },
  };
}

type ResponseError = Error & (InvariantError | RequestError);

const { error }: ResponseError = { error: { message: "Test", name: "Error" } };

if (error.name === "InvariantError") {
  console.log(error.message);
} else if (error.name === "RequestError") {
  console.log(error.response.message);
} else {
  console.log(error.message); // <-- The issue - "Property 'message' does not exist on type 'never'. (2339)"
}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source