我有以下代码:
function inferTest<T>(factory: (setter: (setterFn: (arg: NoInfer<T>) => NoInfer<T>) => void) => T) {
return factory(null!);
}
const inferred = inferTest((setter) => ({
count: 0,
increment: () => setter(state => ({ count: state.count + 1 })) // 'state' is of type 'unknown'.
}));
console.log(inferred.count); // 'inferred' is of type 'unknown'.
我希望编译器将类型T
推断为
{
count: number,
increment: () => void,
}
然而,由于返回类型factory
中存在increment
属性,因此编译器无法推断类型T
,而是将unknown
指定为类型.这会导致两个编译器错误:
'state' is of type 'unknown'.
'inferred' is of type 'unknown'.
如果您删除increment
属性,那么它可以正常工作:
function inferTest<T>(factory: (setter: (setterFn: (arg: NoInfer<T>) => NoInfer<T>) => void) => T) {
return factory(null!);
}
const inferred = inferTest(() => ({
count: 0
}));
console.log(inferred.count);
我很好奇为什么在factory
的定义中使用setter
参数会导致编译器放弃推理,特别是考虑到除了T
的一个外观之外的所有外观上都使用了NoInfer
类型.有人知道这里发生了什么吗?