gpt4 book ai didi

javascript - 为什么 Typescript 不能推断可选参数的函数参数类型?

转载 作者:行者123 更新时间:2023-12-03 17:09:13 26 4
gpt4 key购买 nike

我认为在 TS Playground 上尝试会更清楚:

function identity<T extends (...args: any[]) => any>(fn: T): T {
return fn;
}

function fn(args: {
cb: (foo: number) => void,
}) {}

fn({
cb: identity((foo /* infers number */) => {}),
});

function fn2(args: {
cb?: (foo: number) => void,
}) {}

fn2({
cb: identity((foo /* doesn't infer number */) => {}),
});

function fn3(args: {
cb: (foo: number) => void,
} | {}) {}

fn3({
cb: identity((foo /* infers number */) => {}),
});
对于 fnfn3 , TS 能够推断出 foonumber .但是,对于 fn2 , TS 刚刚输入 fooany . fn2 的输入和 fn3在功能上是相同的,所以我想知道为什么 TS 无法推断 foo 的类型.
实际的用例是 React 的 useCallback ,我试图推断通过 useCallback 的函数的参数类型.
为什么 TS 会这样?有没有更简单的解决方案?

最佳答案

我认为这里的关键步骤是推断 identity返回类型:

 let result: ((foo: number) => void | undefined) = identity(...);
由于返回类型的基本约束为 (...args: any[]) => any Typescript 规范的这条规则适用:

The inferred type argument for each type parameter is the union type of the set of inferences made for that type parameter. However, if the union type does not satisfy the constraint of the type parameter, the inferred type argument is instead the constraint.


~ TypeScript Language Specification (outdated), Contextual Signature Instantiation


undefined (可选值)不满足约束,采用约束,T 被推断为 (...args: any[]) => any .
通过删除约束, T gets inferred correctly

关于javascript - 为什么 Typescript 不能推断可选参数的函数参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66929130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com