Rafael Emshoff
Rafael Emshoff

Reputation: 2729

Casting to :any breaks type check

In what scenario is it a good idea for the typescript compiler to accept the following:

const foo: string = 7 as any;

I would expect some error message like Type any is not assignable to type string. I let a bug slip through to production because I missed an implicit cast to any on a computed property.

Upvotes: 0

Views: 177

Answers (1)

Kirill Dmitrenko
Kirill Dmitrenko

Reputation: 3629

any is assignable to anything, that's kind of it's whole point. To understand why it's there it's important to remember that TypeScript is a superset of JavaScript. A lot of JavaScript APIs returns arbitrary objects (such as JSON.*, fetch), and there's no way to write type declarations for them w/o any. Also any is useful for migration of existing code bases from JS to TS.

I let a bug slip through to production because I missed an implicit cast to any on a computed property.

Set strict option in your tsconfig.json to true. That will forbid unknown types from being implicitly cast to any.

Upvotes: 1

Related Questions