gpt4 book ai didi

typescript - 如何使声明的函数根据用法自动推断类型?

转载 作者:行者123 更新时间:2023-12-05 02:36:24 25 4
gpt4 key购买 nike

我觉得这在 typescript 中应该完全可行,但似乎 typescript 没有正确输入它。有什么办法吗?这是一个 super 简单的例子,但我特别希望在将函数传递给接受定义类型回调的 React 组件的 prop 时自动推断参数类型

实际

function constrainingFunction(b: number) {
return b + 1
}

function test(a) { // ERROR: `a` implicitly has an `any` type
constrainingFunction(a)
}

test(1)

预计

function constrainingFunction(b: number) {
return b + 1
}

function test(a) { // `a` should properly be inferred as `number`
constrainingFunction(a)
}

test(1)

最佳答案

参见 microsoft/TypeScript#34738以获得规范的答案。

TypeScript 不执行 contextual typing以这种方式使用函数参数,显然是出于性能原因。根据this comment by the dev lead for the TS team ,

This has been an intentional design constraint since inception; not doing this is a key reason TS performance is remotely acceptable.

还有 this comment在相关问题中:

People have asked us hundreds of times why we don't do this; the answer is that it's architecturally impractical to do this in a way that results in stable, performant checking results in anything other than toy programs.

因此 a 参数需要显式地设置为 annotated作为 number 以便此代码按预期工作而不会出错。


但您不一定需要自己对其进行注释。正如上面的两条评论继续说的那样:

The "infer from usage" refactor will produce a type for you on an as-requested basis.

The "infer from usage" refactor is available for this purpose.

因此 TypeScript 可以从使用中推断类型,但在编译期间不会自动推断。您可以在支持代码操作的 IDE 中专门请求它,例如 Visual StudioThe TypeScript Playground .

如果您选择了有问题的 a 参数,您应该会看到一个灯泡,单击它时会提示“从用法中推断参数类型”:

function constrainingFunction(b: number) {
return b + 1
}
// 💡 [ infer parameter types from usage ]
function test(a) { // ERROR: `a` implicitly has an `any` type
// -------> ~
constrainingFunction(a)
}

test(1)

如果您接受该建议,就会出现所需的显式注释:

function constrainingFunction(b: number) { // <-- magic!
return b + 1
}
function test(a: number) {
constrainingFunction(a)
}

test(1)

补充动画截图:

animated screenshot

所以这对你来说可能是一些安慰。

Playground link to code

关于typescript - 如何使声明的函数根据用法自动推断类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70265711/

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