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

时间:2019-11-16 15:13:18

标签: typescript typescript-generics

给定一个函数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

1 个答案:

答案 0 :(得分:1)

我认为这就是您要寻找的

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

相关问题