TypeScript: "Any" and Generics When to Use Each One?
Vinicius Passos
Senior Developer | Node.JS | Javascript | Typescript | React | AWS | GCP
TypeScript has brought more security and predictability to JavaScript, but when starting to type code, doubts arise about when to use any and generics. Each one has its purpose, and choosing wisely makes a big difference in code quality. Let's explore!
The dreaded any A necessary evil?
The any type allows a variable to accept any value without restrictions. It is powerful but dangerous: when using it, you lose all the benefits of TypeScript.
When to use it?
The problem here is that any allows anything, and TypeScript will not help detect issues.
Generics The best way to avoid any
Generics allow the creation of reusable components while maintaining strong typing without needing to define a specific type in advance. They help prevent the use of any, ensuring type safety while keeping code flexible.
When to use it?
Generics ensure that the expected structure is maintained, avoiding any while keeping flexibility.
Each of these approaches has its moment:
The key to good TypeScript code is balancing pragmatism and security. How have you used generics to avoid any in your projects? Share your experience in the comments!
Data Engineer | Python | SQL | PySpark | Databricks | Azure Certified: 5x
3 周Great content, thank you! ??
Lead Fullstack Engineer | Typescript Software Engineer | Nestjs | Nodejs | Reactjs | AWS
3 周Excellent overview of `any` and generics in TypeScript! A thoughtful comparison that highlights the importance of choosing the right tool for the job to maximize code quality and maintainability.
Senior Mobile Developer | Android Software Engineer | Jetpack Compose | GraphQL | Kotlin | Java | React Native | Swift
3 周Interesting
Fullstack Software Engineer | Node | Typescript | React | Next.js | AWS | Tailwind | NestJS | TDD | Docker
3 周Nice article and approach ! Thanks for sharing! Vinicius Passos Recently a started a migration of a project in JS to TS, uses "any" its realy useful for this approach
Senior React Developer | Full Stack Developer | JavaScript | TypeScript | Node.js
4 周nice, thanks for sharing !