Typescript: generic that extends a type with a generic

后端 未结 2 1890
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 01:58

Say I have an interface

interface Applicative {}

Now I want to define a function f that:

  • takes a funct
相关标签:
2条回答
  • 2021-01-18 02:17

    This is not exactly what you are looking for but it is as close as I think you can get:

    interface Applicative<T> {}
    
    function f<U>(fn: Function, a: U & Applicative<any>): U & Applicative<Function> {
    
        return null;
    }
    

    a will have to be both U (whatever U is) and Applicative<any>. U can not be defined to be a generic type explicitly I am afraid.

    Better typing can be achieved by:

    function f<U, V>(fn: Function, a: U & Applicative<V>): U & Applicative<Function> { }
    

    I am not entirely sure that the return type in my example is exactly what you want. But you should be able to achieve your required result by adding/changing the required interface on the return type e.g.:

    function f<U, V>(fn: Function, a: U & A<V>): U & A<Function>
    function f<U, V>(fn: Function, a: U & A<V>): U & A<Function> & B<V>
    

    Or something similar.

    0 讨论(0)
  • Unfortunately, typescript does not (yet?) implement higher kinded types.

    See https://github.com/Microsoft/TypeScript/issues/1213 for details

    0 讨论(0)
提交回复
热议问题