← All articles

Why You Shouldn't Use 'as' in TypeScript

The Problem With as

TypeScript's as operator lets you tell the compiler "trust me, I know what this is." It's powerful — and dangerously easy to misuse.

This compiles without errors. But if value isn't actually a string? Silent runtime failure.

Where It Goes Wrong

With Fetch

fetch doesn't guarantee the shape of returned data. The API could change, return an error object, or send malformed JSON. Your as assertion silently accepts all of it.

With JSON.parse

Same problem. No runtime validation. If the string doesn't match your type, you won't know until something breaks downstream.

The Solution: Runtime Validation with Zod

zod validates data at runtime, ensuring it matches your expected shape before your code touches it.

With Fetch

With JSON.parse

Now you get a clear error at the boundary — not a mysterious undefined is not a function three layers deep.

When as Is Acceptable

Gradual TypeScript migration. When converting a large JavaScript codebase, temporary as usage maintains compatibility while you incrementally add proper types:

This should be temporary. Replace it with proper validation as migration progresses.

The Takeaway

as tells the compiler to stop helping you. In most cases, that's the opposite of what you want. Use runtime validation at system boundaries — API responses, user input, parsed data — and let TypeScript do its job everywhere else.

Originally published on Dev.to →