Typescript: generic that extends a type with a generic

后端 未结 2 1907
隐瞒了意图╮
隐瞒了意图╮ 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 {}
    
    function f(fn: Function, a: U & Applicative): U & Applicative {
    
        return null;
    }
    

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

    Better typing can be achieved by:

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

    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(fn: Function, a: U & A): U & A
    function f(fn: Function, a: U & A): U & A & B
    

    Or something similar.

提交回复
热议问题