How do I express this in Typescript?

前端 未结 3 1592

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

    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

提交回复
热议问题