01.Zero-Tolerance for `any` & Mastering `unknown`
The easiest way to degrade a TypeScript codebase is allowing developers to bypass compiler errors with any. In strict production repositories, any should be prohibited via ESLint rules (@typescript-eslint/no-explicit-any: 'error').
When accepting unstructured or external payloads (such as API responses or user form inputs), always type the variable as unknown, then narrow it using type guards or Zod schemas.
02.Discriminated Unions for Impossible State Prevention
One of TypeScript’s most powerful design features is the discriminated union. Instead of managing multiple optional booleans (isLoading, isError, isSuccess), represent state as an explicit tagged union:
type AsyncState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: string };
function renderUI(state: AsyncState<User>) {
switch (state.status) {
case 'loading': return <Spinner />;
case 'success': return <Profile user={state.data} />;
case 'error': return <Alert message={state.error} />;
case 'idle': return null;
}
}03.Bridging Compile-Time & Runtime with Zod
TypeScript interfaces disappear once compiled to JavaScript. To validate HTTP incoming payloads, environment variables, or database responses at runtime, define your schemas in Zod and infer TypeScript types directly:
import { z } from 'zod';
export const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
role: z.enum(['admin', 'member', 'guest']),
createdAt: z.coerce.date(),
});
// Single source of truth for compile-time type!
export type User = z.infer<typeof UserSchema>;Frequently Asked Questions
Why is TypeScript alone not enough for runtime safety?
TypeScript is strictly a compile-time tool; types are erased in output JavaScript. Without runtime validators like Zod, corrupt data from external APIs or forms can cause unexpected runtime crashes.