DEV Community

How to Write Better TypeScript Code: Best Practices for Clean, Effective, and Scalable Code

Yug Jadvani on November 02, 2024

Introduction As TypeScript has grown in popularity, developers have embraced it for its type safety, scalability, and powerful tooling i...
Collapse
 
damian_cyrus profile image
Damian Cyrus

Good sum up.

This is my experience and opinion, but I don't use: 6. Define Return Types Explicitly.
I do it only when there is more than one return type. If a single type is expected, and the function is clear about it, then I leave it out. TypeScript is good with it. It makes the code more readable (for me). Simple functions stay nice and clean without too much pepper included into the code, staying closer to JavaScript.

If you do unit tests and code coverage, then these simple return types are fast covered, too. The IDE also gives hints about the return type.

That is, of course, possible with simple projects/code with less developers, or just one, and trust in their skills. For bigger teams I also suggest more strictness as a rule for safety and consistency.

The thanks for the article. 🙂

Collapse
 
yugjadvani profile image
Yug Jadvani

Your Welcome @damian_cyrus

Collapse
 
worx profile image
Worx R

This article feels AI generated again. Do NOT use enums in TypeScript, check out this actually well written article which explains why: totaltypescript.com/why-i-dont-lik...

Collapse
 
rappayne profile image
Rap Payne

I came to the comments to say exactly this. Do not use enums in TypeScript. In fact, never use TypeScript syntax when JavaScript syntax will do the trick.

Collapse
 
yugjadvani profile image
Yug Jadvani

Absolutely, that’s a solid approach! Using plain JavaScript syntax in TypeScript where possible keeps the code simple, more flexible, and easier for others to read and maintain. TypeScript’s strength really shines when it enhances, rather than complicates, JavaScript. Thanks for sharing this, it’s a great reminder to stick with simplicity where it serves best!

Collapse
 
yugjadvani profile image
Yug Jadvani

You're absolutely right! Enums in TypeScript can introduce subtle issues, especially with complex codebases or when targeting JavaScript runtime compatibility. They can lead to unexpected bugs and make refactoring trickier than it needs to be. Using union types or literal types often achieves the same purpose with less overhead and better type safety. Thanks for pointing it out, and I'll definitely keep this perspective in mind for future articles! 🙌

Collapse
 
glensc profile image
Elan Ruusamäe

Also feels like comment responses are ai generated..even the absolutely and you are right exclamations are there.

Collapse
 
brense profile image
Rense Bakker

Good list, but I disagree on number 6. One of the best things about typescript is how good it is at inferring types. This is way better than strictly typed languages, like Java, where the type system (severely) limits the implementation. You get the same amount of type safety without any of the frustration. Inferred doesn't mean its not typed. The only time I use explicit return types is when doing method overloading.

Collapse
 
kwoodgmr profile image
kwood-gmr

But... if you specify the return type - you also protect against unintended return types. I find it depends on the complexity. I don't specify for obvious - but do when it could have accidental drift.

Collapse
 
yugjadvani profile image
Yug Jadvani

Absolutely, that's a great point! Specifying return types can definitely serve as a guardrail, especially when working with more complex functions or code that could easily evolve and "drift" over time. It’s all about balancing clarity and flexibility—explicit types can be a safety net in places where the logic might change, but for simpler, more obvious functions, inference keeps things clean and readable. Thanks for adding that perspective! 👍

Collapse
 
yugjadvani profile image
Yug Jadvani

Great point! TypeScript’s type inference is indeed powerful, and leveraging it can make the code cleaner and often more maintainable without losing type safety. Explicit return types can sometimes feel restrictive, especially when TypeScript does such a great job of understanding context on its own. Thanks for highlighting this – it's a solid reminder to strike the right balance and only enforce explicit typing where it adds clarity or when overloads are in play. Appreciate your input! 👏

Collapse
 
kwoodgmr profile image
kwood-gmr

Strongly disagree with number 8. I would say don't use Enums. A much better system is to use something along the lines of:
`export const UserRole {
Admin = "ADMIN",
User = "USER",
Guest = "GUEST",
} as const

export type UserRole = (typeof UserRole) keyof UserRole`

For more thorough explanation:
blog.logrocket.com/why-typescript-...
medium.com/@alex.roh/typescript-en...

Collapse
 
yugjadvani profile image
Yug Jadvani

You make a solid case! Using as const with objects and keyof is often a much cleaner and type-safe way to define constants like user roles in TypeScript, without some of the quirks that come with enums. This approach offers better flexibility and reduces potential issues when compiling to JavaScript. Thank you for sharing those resources—I'll take a closer look and keep this technique in mind for future posts! 👏

Collapse
 
trplx_gaming profile image
Gabriel Ibe

Really nice read NGL 🤝

10. Keep Functions pure....
Yeah I don't do that😅, there are functions that can perform side effects whilst still being easy to debug based on their naming. And even in the case of modules, side effects are ok. I'm speaking from game dev experience

7. Null Coalescing and Safety
Your implementation of it was very concise and shows the minimum potential for that in large scale project development

And yes, I define the return type of my functions🤓

Collapse
 
snowman524 profile image
Snowman

Good article!

Collapse
 
yugjadvani profile image
Yug Jadvani

You're very welcome! 😊 If you have any more questions or need further insights, feel free to reach out. Happy coding! 🚀

Collapse
 
snowman524 profile image
Snowman

Thank you very much.

Collapse
 
mdrijwan profile image
Md Rijwan Razzaq Matin

Nicely compiled. Good one Yug!

Collapse
 
yugjadvani profile image
Yug Jadvani

You're very welcome! 😊 If you have any more questions or need further insights, feel free to reach out. Happy coding! 🚀

Collapse
 
glensc profile image
Elan Ruusamäe

Your 9 doesn't follow previous rule no 6. How do you solve following both?

Collapse
 
yugjadvani profile image
Yug Jadvani

Use explicit return types on complex, reusable functions where unintended return types could introduce bugs—especially in large codebases.

For functions that need exhaustive checks (like switch statements on union types), you can let TypeScript infer the return type if the function is self-contained and straightforward. If the function grows or reusability becomes important, you can then add an explicit return type.

Collapse
 
nozibul_islam_113b1d5334f profile image
Nozibul Islam

Great, thank you.

Collapse
 
yugjadvani profile image
Yug Jadvani

You're very welcome! 😊 If you have any more questions or need further insights, feel free to reach out. Happy coding! 🚀

Collapse
 
wizard798 profile image
Wizard

Just amazing tips and tricks for making code nore effective, readable and easily understandable.

Collapse
 
yugjadvani profile image
Yug Jadvani

Thanks so much! 😊 Glad you found the tips helpful. Writing code that's both effective and easy to understand is always the goal. Appreciate the positive feedback! 🙌✨