我现在阅读了很多关于 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 themouseEvent
parameter, which does contain abutton
property, but not akangaroo
property.
因此,上下文类型不是通过分配给它的内容来推断变量的类型,而是通过变量的位置来推断变量的类型。
整个页面可能值得一读。
关于typescript - 上下文类型只是类型推断的另一个术语吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57464541/