Skip to main content

Any

Warning: Do not mistake any with mixed. It's also not the same as empty.

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.

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({});

There are only a couple of scenarios where you might consider using any:

  1. 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).
  2. 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.

You can ban any by enabling the unclear-type lint rule.

You can use the coverage command to identify code typed as any.

Avoid leaking 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.

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}

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}

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

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}

Now your code will not leak any.