首页 > 解决方案 > 打字稿将类型分配给另一个类型中的类型的对象

问题描述

我有这样的类型:

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

此操作通过管道(此时我无法重构),并且在另一个函数中,我需要将有效负载类型分配给对象。

我可以轻松获得返回类型reorderPiece

x:ReturnType<typeof reorderPiece>和访问x.payload。但是我如何分配有效载荷的类型(这是{id:string, otherId:string, contentId:string}通过从类型中自动选择该类型来自动分配的,这样ReturnType<typeof reorderPiece>x可以拥有该类型并且我可以将其访问为or ?typeof ReturnType<typeof reorderPiece>.payloadx{id:string, otherId:string, contentId:string}x.idx.contentId

我知道我总是可以显式(或隐式)编写此类类型并在我的方法中使用该类型,但我想知道是否可以从方法中自动选择该类型。

(我在 Typescript 3.7.5 上)

标签: typescripttypescript3.0

解决方案


您可以使用查找类型:

从语法上讲,它们看起来与元素访问完全一样,但写成类型

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

操场


推荐阅读