Daniel Santos
Daniel Santos

Reputation: 911

Is this behavior of "any" a TypeScript Type System Bug?

I expect the TypeScript compiler to fail given this code:

function test(f: string) {
    console.log(typeof f);
}

const foo: any = ["Test"];
test(foo);

const boo = "test";
test(boo);

The output is:

object
string

I am hesitant to write a bug on GitHub as I am not TypeScript expert. What do folks think?

Playground Link

Upvotes: 1

Views: 525

Answers (1)

jcalz
jcalz

Reputation: 328568

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.

TypeScript ESLint can be configured to disallow annotating a value as type any via the no-explicit-any rule. This would cause you to get an error something like this:

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

Upvotes: 4

Related Questions