Home > Software engineering >  Picking a specific return Type from a type that contains multiples in TypeScript
Picking a specific return Type from a type that contains multiples in TypeScript

Time:09-27

I have a type that contains multiple different return types and I would like to create a new Type based on one of its types like this:

type GetServerSidePropsResult<P> = {
    props: P | Promise<P>;
} | {
    redirect: Record<string, any>;
} | {
    notFound: true;
}

type Redirect<P> = Pick<GetServerSidePropsResult<P>, { redirect }>

This syntax does not work, and I was wondering:

  • Is this even possible?
  • If yes, is it also possible to get rid of the P since we don't need it?

CodePudding user response:

You can do this with the Extract utility:

type Redirect<P> = Extract<GetServerSidePropsResult<P>, { redirect: any }>

Note that you need to specify a type for the property, but you can just use any for that to allow any of the types that returns that property.

As for removing the type parameter, you can use any for the value in GetServerSidePropsResult<P> and then remove it from Redirect

type Redirect = Extract<GetServerSidePropsResult<any>, { redirect: any }>
  • Related