首页 > 解决方案 > 打字稿:每个键的映射对象值类型

问题描述

在下面的示例代码中:

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<>实用程序,但我不知道如何使用它来映射每个道具obj

总之,我想numberArg成为 typenumber并且stringArg成为 type string

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

标签: typescript

解决方案


使用映射对象类型

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

游乐场链接


推荐阅读