TypeScript Best Practices
Writing good TypeScript is about more than just adding type annotations everywhere — it's about using the type system to genuinely prevent bugs while keeping code readable and maintainable.
Following a few consistent habits, such as enabling strict mode, avoiding unnecessary `any`, and preferring precise types, will make your TypeScript projects much easier to work with as they grow.
// Best practices, not new syntaxKey habits
Enable `strict` mode in tsconfig.json from the start of a project. Prefer `unknown` over `any` when a type is genuinely uncertain. Let TypeScript infer simple variable types instead of over-annotating.
Structuring types
Use interfaces or type aliases to name and reuse complex shapes instead of repeating them. Keep functions small with clear parameter and return types, especially in shared or public code.
interface User {
name: string;
age: number;
}
function isAdult(user: User): boolean {
return user.age >= 18;
}
console.log(isAdult({ name: "Zoe", age: 20 }));trueA named interface and a small function with clear types make this code easy to read and reuse.
function parseInput(value: unknown): string {
if (typeof value === "string") {
return value.trim();
}
return String(value);
}
console.log(parseInput(" hi "));
console.log(parseInput(42));hi
42Using unknown instead of any forces a safe type check before the value is used.
Key points
- Enable strict mode in every new TypeScript project.
- Prefer unknown over any when a type is genuinely uncertain.
- Let TypeScript infer obvious types instead of over-annotating everything.
- Reuse interfaces and type aliases instead of repeating complex shapes.
