任何类型
警告:不要将
any
与mixed
混淆。它也和empty
不一样。¥Warning: Do not mistake
any
withmixed
. It's also not the same asempty
.
如果你想要一种选择不使用类型检查器的方法,any
就是这样做的方法。使用 any
是完全不安全的,应尽可能避免。
¥If you want a way to opt-out of using the type checker, any
is the way to do
it. Using any
is completely unsafe, and should be avoided whenever
possible.
例如,下面的代码不会报任何错误:
¥For example, the following code will not report any errors:
1function add(one: any, two: any): number {2 return one + two;3}4
5add(1, 2); // Works.6add("1", "2"); // Works.7add({}, []); // Works.
即使是会导致运行时错误的代码也不会被 Flow 捕获:
¥Even code that will cause runtime errors will not be caught by Flow:
1function getNestedProperty(obj: any) {2 return obj.foo.bar.baz;3}4
5getNestedProperty({});
只有几种情况你可以考虑使用 any
:
¥There are only a couple of scenarios where you might consider using any
:
当你正在将现有代码转换为使用 Flow 类型时,并且当前无法检查代码类型(可能需要首先转换其他代码)。
¥When you are in the process of converting existing code to using Flow types and you are currently blocked on having the code type checked (maybe other code needs to be converted first).
当你确定你的代码可以工作并且由于某种原因 Flow 无法正确键入检查它时。Flow 无法静态键入 JavaScript 中的习语(数量正在减少)。
¥When you are certain your code works and for some reason Flow is unable to type check it correctly. There are a (decreasing) number of idioms in JavaScript that Flow is unable to statically type.
你可以通过启用 unclear-type
lint 规则来禁止 any
。
¥You can ban any
by enabling the unclear-type
lint rule.
你可以使用 覆盖范围 命令来识别键入为 any
的代码。
¥You can use the coverage command to identify code typed as any
.
避免泄漏 any
¥Avoid leaking any
当你有一个类型为 any
的值时,你可以使 Flow 推断 any
以获取你执行的所有操作的结果。
¥When you have a value with the type any
, you can cause Flow to infer any
for the results of all of the operations you perform.
例如,如果你获取类型为 any
的对象的属性,则结果值也将具有类型 any
。
¥For example, if you get a property on an object typed any
, the resulting
value will also have the type any
.
1function fn(obj: any) {2 let foo = obj.foo; // Results in `any` type3}
然后,你可以在另一个操作中使用结果值,例如将其像数字一样相加,结果也将是 any
。
¥You could then use the resulting value in another operation, such as adding it
as if it were a number and the result will also be any
.
1function fn(obj: any) {2 let foo = obj.foo; // Results in `any` type3 let bar = foo * 2; // Results in `any` type4}
你可以继续此过程,直到 any
泄漏到你的整个代码中为止。
¥You could continue this process until any
has leaked all over your code.
1function fn(obj: any) {2 let foo = obj.foo;3 let bar = foo * 2;4 return bar; // Results in `any` type5}6
7let bar = fn({ foo: 2 }); // Results in `any` type8let baz = "baz:" + bar; // Results in `any` type
通过将 any
转换为另一种类型来尽快切断 any
可以防止这种情况发生。
¥Prevent this from happening by cutting any
off as soon as possible by casting
it to another type.
1function fn(obj: any) {2 let foo: number = obj.foo;3}
现在你的代码就不会泄露 any
了。
¥Now your code will not leak any
.