1

Is it possible in TypeScript to map an objects values to another type that uses the actual type of the entry in the result?

Not sure how to describe it exactly, but here is what I'm trying to achieve:

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
}

I'm trying to "reuse" the types from the source objects keys in the returned objects keys while performing some sort of transformation. In my case I want to wrap it in a function, but such a mechanism could possibly also return other aggregate types such as number[] or string[].

I'd like to do this in a generic way so that I can generate function types based on the keys of any object.

1 Answer 1

3

Mapped type is what you’re looking for.

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

function toFunctions<T>(source: T): MapToFuncs<T> { … }
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. This seems to be exactly what I need!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.