TypeScript:在保留类型信息的同时重新映射对象中的值

时间:2020-05-04 12:33:41

标签: typescript types

在TypeScript中是否可以将对象值映射到使用结果中条目的实际类型的另一种类型?

不确定如何准确地描述它,但这是我想要实现的目标:

const obj = {
    a: 1,
    b: true,
    c: "foo"
}

const result = toFunctions(obj)

// Type of result would be:
{
    a: (input: number) => any // because a was of type number
    b: (input: boolean) => any // because b was of type boolean
    c: (input: string) => any // because c was of type string
}

我试图在执行某种转换的同时“重用”返回对象键中源对象键的类型。就我而言,我想将其包装在一个函数中,但是这种机制也可能返回其他聚合类型,例如number[]string[]

我想以一种通用的方式执行此操作,以便我可以基于任何对象的键生成函数类型。

1 个答案:

答案 0 :(得分:2)

Mapped type是您要寻找的。

type MapToFuncs<T> = {
  [K in keyof T]: (arg: T[K]) => any
}

function toFunctions<T>(source: T): MapToFuncs<T> { … }