10 TypeScript Habits Every JavaScript Developer Should Build 🚀
Source: Dev.to
TypeScript isn’t just another tool — it’s your debugging assistant, documentation system, and code safety net rolled into one. These 10 habits will change the way you code forever.
1. Enable Strict Mode
Always enable strict mode in your tsconfig.json to get the most comprehensive type‑checking.
{
"compilerOptions": {
"strict": true
// …other options
}
}
2. Define Interfaces, Not Just Types
While type aliases and interface declarations can both describe object shapes, interfaces are extendable and ideal for defining contracts.
interface User {
id: number;
name: string;
email: string;
}
3. Avoid any at All Costs
Using any defeats the purpose of TypeScript. Prefer unknown, never, or appropriate union types instead.
function process(value: unknown) {
// narrow the type before using it
}
4. Leverage Utility Types (Pick, Omit, Partial)
TypeScript’s built‑in utility types let you transform existing types efficiently.
type User = { id: number; name: string; email: string };
type PartialUser = Partial; // all fields optional
type UserName = Pick; // only the name field
type UserWithoutEmail = Omit; // all except email
5. Use Type Guards
typeof, instanceof, and custom checks allow you to safely narrow union types.
function isString(value: unknown): value is string {
return typeof value === "string";
}
// Usage
if (isString(someValue)) {
// `someValue` is now typed as `string`
}
6. Explicitly Declare Function Return Types
Always specify what a function returns to avoid accidental any inference.
function getUser(): User {
// implementation…
return { id: 1, name: "Alice", email: "alice@example.com" };
}
7. Use Enums for Fixed Sets of Values
Enums make code more readable and reduce the risk of typos compared to magic strings or numbers.
enum Role {
Admin = "ADMIN",
User = "USER",
}
8. Write Reusable Code with Generics
Generics let you create flexible, type‑safe abstractions.
function identity(value: T): T {
return value;
}
// Example
const num = identity(42);
const str = identity("hello");
9. Validate External Data
Never trust external data blindly; define explicit shapes for API responses.
interface ApiResponse {
success: boolean;
data: User[];
}
10. Trust TypeScript’s Inference Engine
TypeScript can often infer types correctly, reducing boilerplate while keeping safety.
const users = [] as User[]; // inferred as User[]
Final Thought
TypeScript isn’t about writing more code — it’s about writing safer, smarter, and more predictable code, saving hours of debugging while keeping your codebase clean and maintainable.