简体   繁体   English

typescript --strictNullChecks与flow的null检查

[英]typescript --strictNullChecks vs. flow's null checking

If I run "typescript --strictNullChecks" over the code below, I get no errors. 如果我在下面的代码上运行“typescript --strictNullChecks”,我没有错误。 If I run flow over it, it gives me an error about type incompatibility of null vs. number. 如果我在它上面运行流程,它会给我一个关于null与number的类型不兼容的错误。 Why doesn't typescript also error on this? 为什么打字稿也没有错误呢? Is that a feature or an issue worth logging? 这是一项值得记录的功能还是一个问题?

// @flow
var f = function f( x ) {
    var y = x * 2;
}
f(null);

TypeScript doesn't do call site analysis. TypeScript不进行调用站点分析。

TypeScript sees this, which is OK: TypeScript看到了这个,这没关系:

var f = function f( x: any ) {
    var y = x * 2;
}
f(null);

Flow sees: Flow看到:

var f = function f( x: ??? ) {
    var y = x * 2;
}
f(null);

where ??? 哪里??? is determined by looking at the calls in the current file. 通过查看当前文件中的调用来确定。 In this case x has the bare type null and is in error. 在这种情况下, x的裸类型为null并且出错。

Why doesn't TypeScript infer types from call sites? 为什么TypeScript不会从呼叫站点推断出类型? In general, the error messages a computer can generate from doing this are vague -- what you often see in Flow is that you pass the wrong kind of argument to a function, get an error in the body of the correctly-implemented function (or a downstream function), then have to work backwards to see where the offending argument originated. 通常,计算机可以通过这样做生成的错误消息是模糊的 - 您经常在Flow中看到的是您将错误类型的参数传递给函数,在正确实现的函数中获取错误(或一个下游函数),然后必须向后工作以查看有问题的参数的起源。 Sometimes this just isn't clear -- if half your code wrote fileName and half your code wrote filename and you pass a mix of those objects around, who's to say who's incorrect? 有时候这一点并不清楚 - 如果你的代码中有一半写了fileName而你的代码中有一半写了filename而你传递了这些对象的混合,谁会说谁不正确? The TypeScript answer is "put a type annotation explaining what you intended" so that you can get high-specificity errors. TypeScript答案是“放置一个类型注释来解释您的意图”,以便您可以获得高特异性错误。

And because this analysis is more expensive, it's not well-suited for whole-program analysis. 而且因为这种分析更加昂贵,所以它不适合整个程序分析。 So Flow only does this inference on a per-file basis, which means you generally want to have type annotations on every function at the "boundary" of a file and the files it interacts with. 因此Flow仅在每个文件的基础上进行此推断,这意味着您通常希望在文件的“边界”和与其交互的文件的每个函数上都有类型注释。 And since those boundaries are where most of the bugs are, it doesn't always buy you as much as it might seem at first blush. 而且由于这些边界是大多数错误的地方,它并不总是像乍一看那样买到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM