打字稿将类型从另一种类型中的类型分配给对象
Typescript assign type to an object from a type within another type
我有这样的类型:
export function reorderPiece(contentId:string, id:string, otherId:string){
return {
type: REORDER_PIECE_PENDING,
payload: {id, otherId, contentId}
}
}
此操作通过一个管道(此时我无法重构)并且在另一个函数中我需要将类型的有效负载分配给一个对象。
我可以轻松获得 return 类型的 reorderPiece
:
x:ReturnType<typeof reorderPiece>
并访问 x.payload
。但是我如何分配有效负载类型(通过从类型 ReturnType<typeof reorderPiece>
中选择该类型自动分配 {id:string, otherId:string, contentId:string}
以便 x
类似于 typeof ReturnType<typeof reorderPiece>.payload
这样 x
将具有 {id:string, otherId:string, contentId:string}
类型,我可以将其作为 x.id
或 x.contentId
?
访问
我知道我总是可以显式(或隐式)编写此类类型并在我的方法中使用该类型,但我想知道是否可以从方法中自动选择该类型。
(我使用的是 Typescript 3.7.5)
您可以使用 lookup 输入:
Syntactically, they look exactly like an element access, but are written as types
declare const x: ReturnType<typeof reorderPiece>['payload'];
我有这样的类型:
export function reorderPiece(contentId:string, id:string, otherId:string){
return {
type: REORDER_PIECE_PENDING,
payload: {id, otherId, contentId}
}
}
此操作通过一个管道(此时我无法重构)并且在另一个函数中我需要将类型的有效负载分配给一个对象。
我可以轻松获得 return 类型的 reorderPiece
:
x:ReturnType<typeof reorderPiece>
并访问 x.payload
。但是我如何分配有效负载类型(通过从类型 ReturnType<typeof reorderPiece>
中选择该类型自动分配 {id:string, otherId:string, contentId:string}
以便 x
类似于 typeof ReturnType<typeof reorderPiece>.payload
这样 x
将具有 {id:string, otherId:string, contentId:string}
类型,我可以将其作为 x.id
或 x.contentId
?
我知道我总是可以显式(或隐式)编写此类类型并在我的方法中使用该类型,但我想知道是否可以从方法中自动选择该类型。
(我使用的是 Typescript 3.7.5)
您可以使用 lookup 输入:
Syntactically, they look exactly like an element access, but are written as types
declare const x: ReturnType<typeof reorderPiece>['payload'];