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

标签 typescript

我觉得这在 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/

相关文章:

javascript - 当推送到数组时,Typescript undefined 不是一个对象

angular - 如何检查多条件以将 observable 与 rxjs 连接起来

javascript - 为什么以及如何使用 Angular2/Typescript 模型?

angular - 如何防止 Angular 中的多个订阅调用?

typescript - atom-typescript - 为什么无法识别这些 Typescript 配置选项?

javascript - 为普通函数添加 d.ts,它返回一个包装函数的函数

javascript - Karma 是否会针对 Angular 和 Jasmine 的 future 版本进行更新?

node.js - 如何使用cqrs模块在nestjs中进行查询?

TypeScript 构建一个 Promise.all 类函数 - 重载签名与函数实现不兼容

html - Angular2 - 在模板之前获取组件html