在下面的代码片段中,尽管有一个隐式类型化为any
的参数,typescript不会发出任何错误。
declare function constrainedHOF<T extends (...args: any[]) => any>(callback: T): T;
// x is implicitly any, but typescript does not complain
const hof = constrainedHOF(x => {
console.log(x);
});
我的猜测是,问题出在类型约束T extends (...args: any[]) => any
,它使typescript认为它是一个显式的any
。
如何正确地解决这个问题,既保持泛型类型约束为“任何类型的函数”,又使typescript在constrainedHOF
中遇到意外的无类型回调时抱怨隐式any
在最新的稳定Typescript 3.9.2中测试。
我准备了一个Playground Link来演示这个问题,包括检查这个问题是否真的带有泛型约束。
转载请注明出处:http://www.sxboan.com/article/20230330/973832.html