我正在尝试为一个具有单个回调参数(也是一个函数)的函数创建一个类型,以便该回调的参数类型仅限于
对象
只是。
但是我得到了一个类型错误。代码如下:
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
链接