TGViewer
HowProgrammingWorks - JavaScript and Node.js Programming HowProgrammingWorks - JavaScript and Node.js Programming @howprogrammingworks · 6.52K subscribers
Post #1683 11.1K
⭐️ Good and bad cases for TypeScript union types based on JavaScript V8 optimizations

👍 Good cases for union types:
- Union of strings instead of enum:
type Direction = 'north' | 'south' | 'east' | 'west';
- Union of numeric as status or result code: type
StatusCode = 200 | 201 | 204 | 400 | 500;
- Union with shared properties:
type MailTarget = User | Company; (both with email)
- Union with common method:
type Thenable = Promise | Query; (both with then method)

👎 Bad cases for union types:

- Polymorphic object shapes causing depots:
type Something = User | Socket | string;
- Requiring extensive "if"-logic and type checking:
type Input = string | number | boolean;
- Inconsistent return types:
function getData(id: number): string | string[];
- Mixed primitives and objects:
type Value = number | { value: number };
- Сontradictory members:
type Person = { name: string; } | { name: number[] };
- Union types that include any:
type FlexibleType = number | any;
- Incompatible contracts:
type Handler = (() => string) | ((event: Event, data: any) => void);

🎁 Empty value for primitive types and reference types:
- Use null for empty reference types: Object, Function, Array, etc...
- Use undefined for empty primitive types: string, number, boolean, bigint
- Avoid mixing symbols with other types in unions
  • 👍 36
  • ❤ 9
  • 🤯 2
  • 🔥 1
More from @howprogrammingworks
  1. Oct 6, 2026Post #2188
  2. Oct 4, 2026На кого учиться, если все профессии отберут роботы? Где пределы экспансии искусственного и…
  3. Oct 4, 2026Объем текста и объем кода должны заставлять нас не махнуть рукой, а заставлять ии делать м…
  4. Oct 3, 2026https://youtu.be/I5ILntVSjkQ
  5. Oct 2, 2026Dashboard with real-time monitoring Released in reslop v0.2.6 https://github.com/tshemsedi…
  6. Oct 2, 2026video post
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →