【问题标题】:Typescript: map object value type for each key打字稿:每个键的映射对象值类型
【发布时间】:2021-04-02 08:37:50
【问题描述】:

在下面的示例代码中:

const obj = {
  a: () => 1,
  b: () => '2'
}

type typeMap = Record<keyof typeof obj, (arg: unknown) => void>

const map: typeMap = {
  a: (numberArg) => numberArg + 1,
  b: (stringArg) => stringArg.length
}

我希望 Typescript 知道 map 对象中的函数参数类型与原始 obj 对象中每个键的返回类型相同。我知道有 ReturnType&lt;&gt; 实用程序,但我不知道如何使用它来映射来自 obj 的每个道具。

总之,我希望numberArg 的类型为numberstringArg 的类型为string

您可以在Typescript Playground打开此代码。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    使用mapped object type

    // alias for convenience
    type ObjType = typeof obj;
    type TypeMap = {
      [K in keyof ObjType]: (arg: ReturnType<ObjType[K]>) => unknown
    };
    

    Playground link

    【讨论】:

    • 太棒了!成功了,非常感谢您的快速回答
    • @Oswaldo 很高兴能帮到你!如果您满意,请mark the answer as accepted 让人们知道问题已得到解答。
    • 是否有正确处理值类型转换的解决方案?此解决方案通过将每个映射字段的类型设置为未知来丢失信息。
    猜你喜欢
    • 2019-11-19
    • 2018-06-18
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2021-03-28
    • 2019-04-11
    • 2019-07-21
    • 1970-01-01
    相关资源
    最近更新 更多