[英]Generic constraint when defining a type
我试图为具有单个回调参数(也是一个函数)的函数提供一种类型,以使该回调的参数类型仅限于对象 。
但是我收到类型错误。 这是代码:
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)
两者有什么区别? 我怎样才能使前一个工作呢?
谢谢!
编辑
游乐场链接
问题在于常规函数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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.