typescript - 上下文类型只是类型推断的另一个术语吗?

标签 typescript

我现在阅读了很多关于 TypeScript 文档的内容,并注意到一些作者会说 上下文输入,而其他人会说 类型推断。有些人会以同样的方式提及它们(看起来它们只是与术语的选择不一致)。一旦我确定它们是相同的东西,我就会阅读一些给人以不同印象的东西。

在这一点上,几乎感觉有些作者自己也不确定。我知道的一件事是我不确定。有人可以解决这个问题吗?

最佳答案

上下文类型是类型推断的一个子集。见 Contextual Typing在文档中:

Contextual Typing

Type inference also works in “the other direction” in some cases in TypeScript. This is known as “contextual typing”. Contextual typing occurs when the type of an expression is implied by its location. For example:

window.onmousedown = function(mouseEvent) {
   console.log(mouseEvent.button);   //<- OK
   console.log(mouseEvent.kangaroo); //<- Error!
};

Here, the Typescript type checker used the type of the Window.onmousedown function to infer the type of the function expression on the right hand side of the assignment. When it did so, it was able to infer the type of the mouseEvent parameter, which does contain a button property, but not a kangaroo property.

因此,上下文类型不是通过分配给它的内容来推断变量的类型,而是通过变量的位置来推断变量的类型。


整个页面可能值得一读。

关于typescript - 上下文类型只是类型推断的另一个术语吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57464541/

相关文章:

typescript - 安装 webpack-dev-server npm 包时 typescript 编译不安全

AngularJs 多次加载

html - 仅显示单击元素 Angular 2 的类

typescript - 通用类部分初始化器

angular - 找不到模块 : Error: Can't resolve '@angular/core'

typescript - 为什么交集会阻止将接受任何类型的值设置为字符串?

javascript - Grafana 5插件开发,如何保存用户数据/面板状态?

javascript - 为什么我不必将 `import` `anti:fake` 放入我的 Meteor 源文件中?

javascript - Angular 右键单击也打开右侧浏览器菜单

javascript - React/TypeScript - 类型 'false | Element' 不可分配给类型 'Element'