简体   繁体   中英

Infer generic type argument from function callback

Given a function foo , the type parameter T is properly inferred as string in this case:

declare function foo<T>(callback: (bar: T) => void): void

// foo<string>(callback: (bar: string) => void): void
// ---> T is inferred string here
foo((bar: string) => { })

However the following sample shows T to be inferred as unknown . So my question is: Why doesn't the type resolve with T nested inside an object type of the callback?

declare function foo2<T>(callback: (bar: { a: T }) => void): void

// foo2<unknown>(callback: (bar: { a: unknown; }) => void): void
// ---> T is inferred unknown here
foo2(({ a: string }) => { })

Sample code

I think this is what you are looking for

declare function foo<T>(callback: (bar: T) => void): void
foo((bar: string) => { })

declare function foo2<T>(callback: (bar: T) => void): void
foo2((a: { a: string }) => {} )

typescript playground

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