Is there a way of extracting a type of a extended type?

Viewed 63

I wonder if there's a way of extracting a type of an existing type(that already had an extended type to it)

Example:

type GameInfo = {
  id: number,
  name: string,
  version: string
} & HttpRequestError;

type HttpRequestError = {
    timestamp?: string,
    status?: number,
    status_code?: number,
    error?: string,
    message?: string,
  };

Now GameInfo has the extended type HttpRequestError. I would like to undo that and only get GameInfo type.

Something like:

const GameInfoWithoutHttpType = GameInfo extract HttpRequestError;

Is this possible?

ThanKS!

3 Answers

Yes, you can use a combination of the Omit utitlity type with keyof HttpRequestError

type GameInfo = {
  id: number,
  name: string,
  version: string
} & HttpRequestError;

type HttpRequestError = {
    timestamp?: string,
    status?: number,
    status_code?: number,
    error?: string,
    message?: string,
};

type WithoutHttp = Omit<GameInfo, keyof HttpRequestError>

If you're using a version >= 3.5, you can achieve that using Omit :

type GameInfoWithoutHttpType = Omit<GameInfo, keyof HttpRequestError>;

Given your types

type GameInfo = {
  id: number,
  name: string,
  version: string
} & HttpRequestError;

type HttpRequestError = {
  timestamp?: string,
  status?: number,
  status_code?: number,
  error?: string,
  message?: string
}; 

Create a utility type that decomposes arbitrary intersection types

type RemoveIntersection<I, R> = I extends R & infer T ? T : I; 

And then apply it to the types in question

type GameInfoWithoutHttpError = RemoveIntersection<GameInfo, HttpRequestError>;

Playground Link

Related