我有这样的类型:
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
类似于typeof ReturnType<typeof reorderPiece>.payload
从而使{{1} }的类型为x
,我可以以{id:string, otherId:string, contentId:string}
或x.id
的身份访问它吗?
我知道我总是可以显式(或隐式)编写这种类型并在我的方法中使用该类型,但我想知道是否有可能自动从方法中选择该类型。
(我正在使用打字稿3.7.5)
答案 0 :(得分:1)
您可以使用lookup类型:
从语法上讲,它们看起来完全像是元素访问,但是被写为类型
declare const x: ReturnType<typeof reorderPiece>['payload'];