Skip to content

Instantly share code, notes, and snippets.

@lukehorvat
Last active June 6, 2020 14:12
Show Gist options
  • Save lukehorvat/ca19d340d9575789587f075fe915ce07 to your computer and use it in GitHub Desktop.
Save lukehorvat/ca19d340d9575789587f075fe915ce07 to your computer and use it in GitHub Desktop.
Convert one mapped type to another. (TypeScript)
type Input<Output> = {
[K in keyof Output]: { foo: () => Output[K] };
};
function convert<Output>(input: Input<Output>): Output {
const keys = Object.keys(input) as (keyof Input<Output>)[];
return keys.reduce(
(output, key) => ({ ...output, [key]: input[key].foo() }),
{} as Output
);
}
const output = convert<{
a: number;
b: string;
c: boolean;
}>({
a: { foo: () => 1 },
b: { foo: () => '!' },
c: { foo: () => true },
});
console.log(output); // = { a: 1, b: '!', c: true }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment