---
title: "Discussion on \"Typescript stories - Generics vs Union types\" | Hashnode"
description: "Discussion on \"Typescript stories - Generics vs Union types\". Who's the winner?"
url: "https://hashnode.com/posts/typescript-stories-generics-vs-union-types/672db701f80fa70a58233268"
---

[Feed](https://hashnode.com/feed) /

Discussion

# [Typescript stories - Generics vs Union types](https://blog.mihaioltean.com/typescript-stories-generics-vs-union-types?utm_source=hashnode&utm_medium=feed)

Who's the winner?

Nov 8, 2024 · 4 min read · blog.mihaioltean.com  
Read the article

-   [#typescript](https://hashnode.com/tag/typescript)
-   [#refactoring](https://hashnode.com/tag/refactoring)
-   [#generics](https://hashnode.com/tag/generics)
-   [#types](https://hashnode.com/tag/types)
-   [#frontend-development](https://hashnode.com/tag/frontend-development)
-   [#backend](https://hashnode.com/tag/backend)

## Written by

[Mihai Oltean](https://hashnode.com/@ltemihai)

@ltemihai · Romania

  
[View profile](https://hashnode.com/@ltemihai)

Software engineer / Angular / C#

Software engineer / Angular / C#

## Responses

Markdown supported · ⌘↵ to post

[Soothfy App](https://hashnode.com/@soothfyapp)

[Nov 9, 2024](https://hashnode.com/posts/typescript-stories-generics-vs-union-types/672db701f80fa70a58233268/comment/672f38c9df2707dca578cb5d)

This article discusses handling varying object shapes in TypeScript while avoiding the use of the `any` type. It explores several approaches:

1.  **Marker Interfaces**: Initially considered, but questioned for their lack of functionality.
2.  **Generics**: Allow for flexible functions but don't enforce type constraints, leading to potential misuse.
3.  **Union Types**: Offer a way to define a fixed set of types with a discriminator for type narrowing, providing better type safety.
4.  **Combining Generics and Union Types**: This approach maintains type inference while allowing for flexibility and strict type checking, especially useful when returning the exact type passed to a function.

The article concludes that understanding when to use each method helps achieve a balance between flexibility, reusability, and type safety.
