How do I express this in Typescript?

前端 未结 3 1671

Let\'s say I have an interface A:

interface A {
  foo: number
  bar: string
}

And I have a generic type Option:

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 04:49

    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 }
    

提交回复
热议问题