You open an old TypeScript file and see a wall of if (user && user.profile && user.profile.address && ...). Your eyes glaze over. Somewhere in the middle, you lose track of what the code was even trying to do. š
We've all been there. The good news? TypeScript has a bunch of small, built-in TypeScript shortcuts that turn long, noisy code into short, clear code. And many developers use TypeScript for years without discovering them.
So here's the question: how much cleaner could your code be if you knew just eight of them? Let's find out. š
What Are TypeScript Shortcuts?
Think about keyboard shortcuts. You could right-click, find "Copy" in a menu, and click it. Or you could press Ctrl + C. Same result, far less effort.
TypeScript shortcuts work the same way. They are small pieces of syntax or built-in types that let you do something in one short line instead of five long ones.
In this post, "shortcuts" means code-level shortcuts: short syntax and built-in helpers. Nothing here is magic, and nothing is hacky. These are all normal, documented TypeScript features. They just don't get talked about enough.
Why TypeScript Shortcuts Matter
Short code isn't automatically good code. But clear short code is a gift to your future self.
Here's what these shortcuts help with:
- Readability: Less noise means the real logic stands out.
- Fewer bugs: Many shortcuts replace error-prone hand-written checks.
- Less repetition: You stop retyping the same types over and over.
- Better code reviews: Teammates can understand your change faster.
- Confidence in interviews and real projects: Knowing these features shows you understand the language, not just the basics.
Imagine renaming a field in one place and having TypeScript update ten related types automatically. That's the kind of calm these shortcuts bring. ā
8 TypeScript Shortcuts With Real-Life Examples
1. Optional Chaining (?.)
You have data from an API, and some parts might be missing. The long way is to check every level by hand.
// The long way
const city =
user && user.profile && user.profile.address && user.profile.address.city;
// The shortcut
const city = user?.profile?.address?.city;
If any step is null or undefined, the whole expression safely returns undefined instead of crashing with "Cannot read properties of undefined."
It also works with functions and arrays:
user.sendEmail?.(); // only calls it if it exists
const first = list?.[0]; // safe array access
Why it helps: API responses are rarely perfect. This is the seatbelt for them. š§
2. Nullish Coalescing (??) and ??=
You want a default value when something is missing. Many of us reach for || first. But there's a catch.
const retries = 0;
const a = retries || 3; // 3 (oops, 0 was a valid value!)
const b = retries ?? 3; // 0 (correct)
|| treats 0, "", and false as "missing." ?? only treats null and undefined as missing. That's usually what you actually mean.
And there's a tiny cousin, ??=, which assigns only if the value is null or undefined:
options.retries ??= 3;
Why it helps: It prevents the classic bug where a valid 0 or empty string gets silently replaced. š”
3. Parameter Properties in Classes
Writing classes can feel like filling out the same form three times: declare the property, accept the parameter, assign it.
// The long way
class UserService {
private apiUrl: string;
public name: string;
constructor(apiUrl: string, name: string) {
this.apiUrl = apiUrl;
this.name = name;
}
}
// The shortcut
class UserService {
constructor(
private apiUrl: string,
public name: string
) {}
}
Adding an access modifier (like private, public, or readonly) in front of a constructor parameter creates the property and assigns it for you.
One honest note: if you turn on the erasableSyntaxOnly compiler option (added in TypeScript 5.8), parameter properties are not allowed. Some setups use it so TypeScript code can run in environments that only strip types. Check your project's config if you see an error.
Why it helps: Dependency-injection-style classes shrink dramatically.
4. as const (Turn Values Into Exact Types)
By default, TypeScript widens your values. A list of strings becomes string[]. Sometimes you want the exact values.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];
// "admin" | "editor" | "viewer"
Now you have one list that works at runtime and as a type. Add a new role to the array, and the type updates by itself.
Why it helps: One source of truth instead of keeping an array and a union type in sync by hand. šÆ
5. The satisfies Operator
Added in TypeScript 4.9, satisfies checks that a value matches a type without erasing what TypeScript knows about it.
// With a type annotation, TypeScript forgets the exact keys
const routesA: Record<string, string> = {
home: "/",
blog: "/blog",
};
routesA.hom; // no error. Typo slips through š¬
// With satisfies, you get the check AND the exact keys
const routesB = {
home: "/",
blog: "/blog",
} satisfies Record<string, string>;
routesB.hom; // Error: property 'hom' does not exist
Why it helps: You get validation and autocomplete together. Great for config objects, route maps, and theme files.
6. Utility Types: Partial, Pick, Omit
Stop rewriting nearly identical types. Build new ones from existing ones.
type User = {
id: number;
name: string;
email: string;
password: string;
};
type PublicUser = Omit<User, "password">;
type UserUpdate = Partial<Omit<User, "id" | "password">>;
type UserPreview = Pick<User, "id" | "name">;
-
Partial<T>makes every field optional. -
Pick<T, K>keeps only the fields you name. -
Omit<T, K>removes the fields you name.
Why it helps: Change User once, and every derived type follows. No more copy-paste drift.
7. typeof and keyof typeof
Why write a type by hand when you already have a real value?
const theme = {
light: "#ffffff",
dark: "#000000",
};
type Theme = typeof theme;
type ThemeName = keyof typeof theme; // "light" | "dark"
typeof (in a type position) grabs the type of a value. keyof gives you its keys as a union.
Why it helps: Your types come straight from your data, so they can't quietly go out of date.
8. ReturnType, Parameters, and Awaited
Sometimes a function already describes the type you need. Reuse it.
async function fetchUser() {
return { id: 1, name: "Sara" };
}
type User = Awaited<ReturnType<typeof fetchUser>>;
// { id: number; name: string }
type FetchArgs = Parameters<typeof fetchUser>;
-
ReturnType<T>gets what a function returns. -
Parameters<T>gets the argument types as a tuple. -
Awaited<T>unwraps a Promise (available since TypeScript 4.5).
Why it helps: When the function changes, your types update automatically.
Quick Bonus Shortcuts ā”
-
Numeric separators:
const limit = 1_000_000;is easier to read than1000000. -
import type:import type { User } from "./types";makes it clear that an import is used only as a type.
Long Way vs Shortcut: Quick Comparison
| Situation | The long way | The shortcut |
|---|---|---|
| Safe nested access | a && a.b && a.b.c |
a?.b?.c |
| Default for missing value | x !== undefined && x !== null ? x : 5 |
x ?? 5 |
| Class property setup | Declare + param + assign | constructor(private x: string) {} |
| Union from an array | Write the array and the union separately |
as const + typeof arr[number]
|
| Type from a value | Hand-written duplicate type | typeof value |
| Type from a function | Hand-written duplicate type | ReturnType<typeof fn> |
Shorter isn't always better. If a shortcut makes the code harder for your teammates to read, the long way may be the kinder choice.
Best Tips: Do's and Don'ts
Do:
- ā
Use
??when0,"", orfalseare valid values. - ā
Use
satisfiesfor config objects so typos get caught. - ā
Derive types from real values with
typeofandas const. - ā
Check your TypeScript version if a feature seems missing. For example,
satisfiesneeds 4.9 or newer. - ā Hover over types in your editor to see what TypeScript really inferred.
Don't:
- ā Chain
?.everywhere "just in case." If a value should always exist, a crash can be a useful signal. - ā Stack five utility types into one unreadable line. Give intermediate types a name.
- ā Use shortcuts just to look clever. Clear beats clever.
Common Mistakes People Make
Mixing up || and ??
This happens because || is familiar from JavaScript. It works until the value is 0 or an empty string. Fix: ask yourself, "Do I only want to replace null and undefined?" If yes, use ??.
Overusing the non-null assertion (!)
Writing user!.name tells TypeScript, "Trust me, it's not null." If you're wrong, the error shows up at runtime. Fix: prefer ?., a real check, or fixing the type at its source.
Forgetting as const makes things read-only
After as const, an array becomes a readonly tuple, so .push() won't compile. This is intentional. Fix: use as const for fixed lists, and a normal array when the list needs to change.
Using a type annotation when satisfies is better
People write const config: Config = {...} out of habit and lose precise keys and values. Fix: try satisfies Config when you want both safety and autocomplete.
Assuming every shortcut works everywhere
Newer features need newer TypeScript versions, and some compiler options (like erasableSyntaxOnly) restrict certain syntax. Fix: check your tsconfig.json and TypeScript version first.
Conclusion
TypeScript shortcuts aren't about writing less code for the sake of it. They're about writing code that's safer, cleaner, and easier to change.
Quick recap:
-
?.and??handle missing data gracefully. - Parameter properties trim down class boilerplate.
-
as constandsatisfieskeep your types precise. - Utility types,
typeof, andReturnTypestop you from repeating yourself.
Pick one shortcut from this list and use it in your next pull request. Small habits add up fast. š
If this post helped, share it with a friend who's learning TypeScript, and let me know in the comments which shortcut surprised you most. For more practical dev posts, visit hamidrazadev.com. Happy coding! š
Section A: Why people would share this post
- It's packed with small tricks readers can use in their very next commit.
- The examples are short, honest, and easy to follow, even for beginners.
- It points out common traps like
||vs??, which many developers have hit. - It's easy to bookmark and send to a teammate who's just starting with TypeScript.
Top comments (0)