TypeScript Tips for Everyday Development
·2 min read·technology
Some TypeScript patterns and features come up constantly in my daily work. Here are the ones I've found most useful.
1. Type Narrowing
One of TypeScript's most powerful features is type narrowing. You can narrow types using typeof, instanceof, and custom type guards:
function processValue(value: string | number) {
if (typeof value === "string") {
// TypeScript knows value is a string here
return value.toUpperCase();
}
// Here it knows it's a number
return value.toFixed(2);
}
2. Utility Types
TypeScript's built-in utility types are incredibly useful:
// Partial - makes all properties optional
type PartialUser = Partial<User>;
// Pick - selects specific properties
type UserName = Pick<User, "firstName" | "lastName">;
// Omit - excludes specific properties
type UserWithoutId = Omit<User, "id">;
3. Discriminated Unions
Discriminated unions offer a clean way to model different states:
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
function handleResult(result: Result<User>) {
if (result.success) {
console.log(result.data); // TypeScript allows access to data
} else {
console.error(result.error); // Only error is available here
}
}
4. as const for Literal Types
as const is really handy for using constant values as literal types:
const ROUTES = {
home: "/",
blog: "/blog",
about: "/about",
} as const;
type Route = (typeof ROUTES)[keyof typeof ROUTES];
// Route = "/" | "/blog" | "/about"
I use these tips regularly in my day-to-day development. TypeScript, when used well, significantly improves both safety and developer experience.