How do I express this in Typescript?

前端 未结 3 1608

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<T> = { map() => T };
    type OptionsHash<T> = { [K in keyof T]: Option<T[K]> };
    
    function optionsFor<T>(structure: T): OptionsHash<T> { ... };
    
    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<T>(hash: OptionsHash<T>): T { ... };
    
    let optionsHash = {
        foo: { map() { return 5; } },
        bar: { map() { return 'x'; } }
    };
    let optionsObject = retreiveOptions(optionsHash);
    // optionsObject is now typed as { foo: number, bar: string }
    
    0 讨论(0)
  • 2021-02-19 04:49

    You are looking for higher-kinded types. Here it is in Scala:

    trait FooBar[M[_]] {
      val foo: M[Integer]
      val bar: M[String]
    }
    
    type Identity[X] = X
    type A = FooBar[Identity]
    type B = FooBar[Option]
    

    You can use any second-order types e.g.:

    type C = FooBar[List]
    

    But these will not compile:

    // type S = FooBar[String] ---> String is a first-order type
    // type M = FooBar[Map]    ---> Map[K, V] is a third-order type
    

    Unfortunately, this has not yet made it into TypeScript but there is an open issue for it: https://github.com/Microsoft/TypeScript/issues/1213

    0 讨论(0)
  • 2021-02-19 04:53

    I haven't looked at TypeScript for a while (I think it was around version 1.0), so I can't really tell if it's there now.

    What you want requires a type system feature called higher kinded types ; it allows one to construct types by passing them as arguments to type constructors, very much like function application, lifted to the type level.

    You'll have to adjust A's definition in order to make this work. Here's how I'd achieve what you want in Haskell :

    -- First, I need a more general definition for A
    data GeneralizedA f = A { foo :: f Int, bar :: f String }
    
    -- So that I can re-encode the original A like this :
    type A = GeneralizedA Identity
    
    -- Guessing what the Option type would be since
    -- Haskell's type system is more precise here :
    data Option a = Option { optionMap :: IO a }
    
    -- And here's the result :
    type B = GeneralizedA Option
    
    0 讨论(0)
提交回复
热议问题