Practical Examples

Real-world TypeScript in Action

Let"s Build Something Real

Here are practical examples you'll actually use in your projects. No complex theory - just useful, everyday TypeScript.

Common Patterns You"ll Use Daily

Loading States
Handle async operations safely
.ts
type LoadingState<T> =
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: string }

const [state, setState] = useState<LoadingState<User>>(
{ status: 'loading' }
)
Optional Chaining
Safe property access
.ts
// Safe navigation
const userName = user?.profile?.name || 'Guest'

// Safe array access
const firstItem = items?.[0]

// Safe method calls
user?.notify?.()
Environment Variables
Type-safe config
.ts
// env.d.ts
declare namespace NodeJS {
interface ProcessEnv {
DATABASE_URL: string
API_KEY: string
NODE_ENV: 'development' | 'production'
}
}

// Now you get autocomplete!
const dbUrl = process.env.DATABASE_URL
Utility Types
Built-in helpers
.ts
// Make all properties optional
type UserUpdate = Partial<User>

// Pick specific properties
type UserSummary = Pick<User, 'name' | 'email'>

// Exclude properties
type PublicUser = Omit<User, 'password'>

Migrating Existing Projects

1

Start Small

Rename one .js file to .tsx and add basic types. You don"t need to convert everything at once.

2

Use 'any' Temporarily

It's okay to use 'any' type while migrating. Replace them gradually as you learn more.

3

Focus on Interfaces

Start by defining interfaces for your main data structures. This gives you the biggest benefit.

Key Takeaways

TypeScript is just JavaScript with types - All your existing knowledge applies
Start with interfaces - Define your data shapes first, everything else follows
Let TypeScript infer when possible - You don"t need to type everything explicitly
Use your IDE - TypeScript"s real power comes from better tooling and autocomplete
Gradual adoption works - Migrate one component at a time, no pressure