代码之家  ›  专栏  ›  技术社区  ›  artemave

定义类型时的泛型约束

  •  0
  • artemave  · 技术社区  · 6 年前

    我正在尝试为一个具有单个回调参数(也是一个函数)的函数创建一个类型,以便该回调的参数类型仅限于 对象 只是。

    但是我得到了一个类型错误。代码如下:

    function aaa(a: { n: number }) { }
    
    type Cb = <T extends object>(a: T) => void
    function ccc(fn: Cb) { }
    // type error - why?
    ccc(aaa)
    

    类型错误:

    Argument of type '(a: { n: number; }) => void' is not assignable to parameter of type 'Fn'.
      Types of parameters 'a' and 'a' are incompatible.
        Type 'T' is not assignable to type '{ n: number; }'.
          Type 'object' is not assignable to type '{ n: number; }'.
            Property 'n' is missing in type '{}'.
    

    类似的泛型约束,但应用于函数定义,效果良好:

    function aaa(a: { n: number }) { }
    
    function bbb<T extends object>(fn: (a: T) => void) { }
    // all good
    bbb(aaa)
    

    编辑

    playground 链接

    1 回复  |  直到 6 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    6 年前

    问题是正则函数 aaa 与泛型函数签名不兼容 Cb .

    你可能想申报 断路器 断路器 具有泛型类型参数

    function aaa(a: { n: number }) { }
    
    type Cb<T extends object> = (a: T) => void
    function ccc<T extends object>(fn: Cb<T>) { }
    // ok
    ccc(aaa)