TypeScript Tips and Tricks
TeD··6 min read
#typescript#javascript#programming
TypeScript Tips and Tricks
TypeScript adds powerful type checking to JavaScript, making your code more robust and easier to maintain. Let's explore some advanced tips and tricks.
Useful Tips
1. Use Type Inference When Possible
Let TypeScript infer types instead of explicitly declaring them:
// Good - TypeScript infers the type
const user = {
name: "John",
age: 30
};
// Unnecessary - type is already inferred
const user: { name: string; age: number } = {
name: "John",
age: 30
};
2. Leverage Union Types
Union types provide flexibility while maintaining type safety:
type Status = "pending" | "success" | "error";
function handleStatus(status: Status) {
switch (status) {
case "pending":
return "Loading...";
case "success":
return "Done!";
case "error":
return "Failed!";
}
}
3. Create Custom Type Guards
Type guards help narrow down types safely:
interface User {
name: string;
email: string;
}
function isUser(obj: any): obj is User {
return obj && typeof obj.name === "string" && typeof obj.email === "string";
}
// Now TypeScript knows the type
if (isUser(data)) {
console.log(data.email); // ✅ Safe
}
Advanced Patterns
Generic Constraints
Use constraints to make generics more powerful:
interface HasId {
id: number;
}
function findById<T extends HasId>(items: T[], id: number): T | undefined {
return items.find(item => item.id === id);
}
Utility Types
TypeScript provides built-in utility types:
type User = {
name: string;
email: string;
age: number;
};
// Make all properties optional
type PartialUser = Partial<User>;
// Make all properties required
type RequiredUser = Required<User>;
// Pick specific properties
type UserPreview = Pick<User, "name" | "email">;
Example
Here's a practical example bringing it all together:
type User = {
name: string;
email: string;
age?: number;
};
function greetUser(user: User) {
console.log(`Hello, ${user.name}!`);
if (user.age) {
console.log(`You are ${user.age} years old.`);
}
}
const newUser: User = {
name: "Alice",
email: "alice@example.com"
};
greetUser(newUser);
Conclusion
TypeScript helps catch errors early and improves code quality. By following these tips and using TypeScript's powerful features, you'll write more maintainable and bug-free code.
Happy coding! 🚀