Last active
June 6, 2020 14:12
-
-
Save lukehorvat/ca19d340d9575789587f075fe915ce07 to your computer and use it in GitHub Desktop.
Convert one mapped type to another. (TypeScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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