Let\'s say I have an interface A
:
interface A {
foo: number
bar: string
}
And I have a generic type Option
:
Good news: With TypeScript 2.1.0, this is now possible via Mapped Types:
type Option = { map() => T };
type OptionsHash = { [K in keyof T]: Option };
function optionsFor(structure: T): OptionsHash { ... };
let input = { foo: 5, bar: 'X' };
let output = optionsFor(input);
// output is now typed as { foo: { map: () => number }, bar: { map: () => string } }
The opposite is also possible:
function retreiveOptions(hash: OptionsHash): T { ... };
let optionsHash = {
foo: { map() { return 5; } },
bar: { map() { return 'x'; } }
};
let optionsObject = retreiveOptions(optionsHash);
// optionsObject is now typed as { foo: number, bar: string }