打字稿:每个键的映射对象值类型

时间:2020-12-23 18:19:21

标签: typescript

在下面的示例代码中:

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 的类型为 number,而 stringArg 的类型为 string

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

1 个答案:

答案 0 :(得分:2)

使用 mapped object type

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

Playground link