2

In the example code bellow:

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
}

I want Typescript to be aware of the function arguments types in the map object to be the same as the return type of each key in the original obj object. I know there is the ReturnType<> utility, but I don't know how to use it to map each prop from obj.

In summary, I want numberArg to be of type number and stringArg to be of type string.

You can open this code in Typescript Playground.

1 Answer 1

2

Use a mapped object type:

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

Playground link

Sign up to request clarification or add additional context in comments.

4 Comments

awesome! that worked, thank you very much for the fast answer
@Oswaldo I'm glad I could help you! If you're satisfied, please mark the answer as accepted so people know that the question's been answered.
Is there a solution that properly handles the type conversion for values? This solution loses information by setting the type for each mapped field to unknown.
as @arlyon mentioned, original return types of each function are lost, is there a workaround to prevent that?

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.