定义类型时的通用约束

时间:2018-11-25 15:13:56

标签: typescript typescript-typings

我正在尝试为具有单个回调参数(也是一个函数)的函数提供一种类型,以使该回调的参数类型仅限于 object

但是我遇到类型错误。这是代码:

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 个答案:

答案 0 :(得分:1)

问题在于常规函数aaa与通用函数签名Cb不兼容。

您可能想将Cb声明为普通函数签名,但是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)