简体   繁体   中英

Generic constraint when defining a type

I am trying to come up with a type for a function with a single callback parameter (also a function) such that the type of the parameter of that callback is restricted to object only.

However I am getting a type error. Here is the code:

function aaa(a: { n: number }) { }

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

Type error:

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 '{}'.

A similar generic constraint, but applied to a function definition, works fine:

function aaa(a: { n: number }) { }

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

What is the difference between the two? And how can I get the former one to work?

Thanks!

EDIT

playground link

The problem is that the regular function aaa is not compatible with the generic function signature Cb .

You probably want to declare Cb as a normal function signature, but with Cb having the generic type parameter

function aaa(a: { n: number }) { }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM