从函数回调中推断泛型类型参数

Infer generic type argument from function callback

给定函数 foo,类型参数 T 在这种情况下被正确推断为 string

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

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

然而,以下示例显示 T 被推断为 unknown。所以我的问题是:为什么不使用嵌套在回调对象类型中的 T 来解析类型?

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

我想这就是您要找的

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