Is this behavior of “any” a TypeScript Type System Bug?

The point of the any type is to opt out of type checking for some parts of your code. It is intentionally unsound; all types are assignable to any and any is assignable to all types (except for never). This is both useful and dangerous. Useful because there are times where it tedious, difficult, or impossible to properly type a piece of valid real-world code, and any is an escape hatch. Dangerous because the compiler cannot tell the difference between valid code typed with any and invalid code typed with any. So in general the advice for any is “use it sparingly”.

If you don’t find such advice sufficient because you don’t trust others or yourself not to write code like test(foo) above, then there is at least one option you might explore before throwing TypeScript away entirely: linting.

Both TSLint and TypeScript ESLint can be configured to disallow annotating a value as type any. TSLint’s rule is called no-any and TypeScript ESLint’s rule is called no-explicit-any. This would cause you to get an error something like this:

// TSLint
const foo: any = ["Test"];
// -----> ~~~~
// ERROR: no-any  Type declaration of 'any' loses type-safety. 
// Consider replacing it with a more precise type.

or possibly

// TypeScript ESLint
const foo: any = ["Test"];
// -----> ~~~~
// warning  Unexpected any. Specify a different type
// @typescript-eslint/no-explicit-any

Okay, hope that helps; good luck!

Leave a Comment