typescripttypescript3.0

Typescript assign type to an object from a type within another type


I've got a type like this:

export function reorderPiece(contentId:string, id:string, otherId:string){
  return {
    type: REORDER_PIECE_PENDING,
    payload: {id, otherId, contentId}
  }
}

This action goes through a pipeline (that I can't refactor at this point) and in another function I need to assign type of payload to an object.

I can get return type of reorderPiece easily:

x:ReturnType<typeof reorderPiece> and access x.payload. But how do I assign type of payload (which is {id:string, otherId:string, contentId:string} automatically by picking that type from the type ReturnType<typeof reorderPiece> so that x is something like typeof ReturnType<typeof reorderPiece>.payload so that x will have the type {id:string, otherId:string, contentId:string} and I can access it as x.id or x.contentId?

I know I can always write such type explicitly (or implicitly) and use that type in my method, but I'm wondering if it's possible to pick that type from method automatically.

(I'm on Typescript 3.7.5)


Solution

  • You can use lookup type:

    Syntactically, they look exactly like an element access, but are written as types

    declare const x: ReturnType<typeof reorderPiece>['payload'];
    

    Playground