TypeScript: "Any" and Generics When to Use Each One?

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?

  • Migrating JavaScript projects to TypeScript: When typing legacy code, any can be a shortcut to avoid massive errors and allow a gradual migration.
  • Rapid prototyping: When the exact typing is not yet clear.

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?

  • To create reusable functions and classes without losing typing.
  • When the exact type should be inferred based on context.
  • When working with APIs or dynamic data structures while ensuring type safety.

Generics ensure that the expected structure is maintained, avoiding any while keeping flexibility.


Each of these approaches has its moment:

  • Use any with caution, only for migration or rapid prototyping.
  • Use generics to create flexible and reusable code while avoiding any and maintaining strong typing.

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!

Jardel Moraes

Data Engineer | Python | SQL | PySpark | Databricks | Azure Certified: 5x

3 周

Great content, thank you! ??

Patrick Cunha

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.

Thiago Nunes Monteiro

Senior Mobile Developer | Android Software Engineer | Jetpack Compose | GraphQL | Kotlin | Java | React Native | Swift

3 周

Interesting

Kaique Perez

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

Bruno Freitas

Senior React Developer | Full Stack Developer | JavaScript | TypeScript | Node.js

4 周

nice, thanks for sharing !

要查看或添加评论,请登录

Vinicius Passos的更多文章

社区洞察

其他会员也浏览了