【问题标题】:Typescript assign type to an object from a type within another type打字稿将类型分配给另一个类型中的类型的对象
【发布时间】:2020-06-29 16:18:31
【问题描述】:

我有一个这样的类型:

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。但是我如何分配有效负载的类型(通过从ReturnType<typeof reorderPiece> 类型中选择该类型自动分配{id:string, otherId:string, contentId:string} 以便x 类似于typeof ReturnType<typeof reorderPiece>.payload 以便x 将具有{id:string, otherId:string, contentId:string} 类型和我可以x.idx.contentId 访问它吗?

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

(我使用的是 Typescript 3.7.5)

【问题讨论】:

    标签: typescript typescript3.0


    【解决方案1】:

    你可以使用lookup输入:

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

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

    Playground

    【讨论】:

    • 这正是我所需要的。谢谢!
    猜你喜欢
    • 2021-10-11
    • 2019-06-08
    • 2020-06-29
    • 2021-12-08
    • 2018-05-06
    • 2019-09-25
    • 1970-01-01
    • 2022-08-14
    • 2022-01-26
    相关资源
    最近更新 更多