AI Hints
Home›TypeScript Tutorial›Habits and Library Types
TypeScript · Lesson 112 of 120

Best Practices

Everyday habits.

⏱ 2 min read▶ Video at 1:28:31🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

You know the language. Now, the habits that make TypeScript code pleasant to work with, for you and your team.

Best Practices
From the video: Best Practices
  • You know the language
  • Now the habits
  • For you and your team

Everyday habits

Keep strict on. Let inference do the simple work. Type the edges of your code, like function parameters and API responses. Prefer unions over enums and booleans. And validate everything from outside.

HabitWhy
strict oncatches the most bugs
Infer localsless noise
Type the edgesclear contracts
Unions over flagsimpossible states impossible
Validate inputtypes vanish at runtime

Impossible states

Two booleans, loading and error, allow a nonsense state where both are true. A union of states, each with a kind, makes nonsense impossible to write.

Flags

  • loading: booleanerror: booleanBoth true?

Union

  • { kind: 'loading' }{ kind: 'error', message }{ kind: 'done', data }

Summary

Keep strict on, type the edges, prefer unions, and validate input. Next, keeping types fast and simple.

Key takeaways
  • strict
  • Type the edges
  • Unions
Next up: Performance of Types — keep it simple