Skip to content
BENIBIX Learn

Generics vs Union Type

People think generics and union types both just mean any type. A union type lists a few kinds a value may be, such as a string or a number, and you must check which one you have. A generic stands for one type that the caller picks. That type is then kept exact all the way through, so a list of strings gives back a string.

Development🧭 Programming Paradigms

Generics

Code written once that works with many types. A stand-in like T fills in.

Generics let you write one function or class for many types. The types are still checked. You write a stand-in type, often called T, in place of a real one. When the code is used, T becomes the real type, like number or string. A function that returns the first item of a list can then work on any list. It also knows exactly what kind of item it hands back.

Example
Lucy writes first<T> to get the first item of a list. Given numbers it gives back a number; given names it gives back a string.
Why it matters
Without generics you write the same list code for each type, or give up type checks. Generics avoid both.
Full entry
Development🧭 Programming Paradigms

Union Type

A type for a value that can be one of a few kinds. It may be text or a number.

A union type says a value can be one of a few types. In TypeScript, string | number means a string or a number. The type checker then makes you handle each case before you use the value. Unions are also how many languages say a value may be missing, like string | null. Rust and Swift build the same idea into enums.

Example
An id field can hold 42 or "A-42". Lucy types it as number | string, and the checker makes her handle both.
Why it matters
Real data often comes in more than one shape. A union names every shape, so none is forgotten.
Full entry

In one line

Generics
Code written once that works with many types. A stand-in like T fills in.
Union Type
A type for a value that can be one of a few kinds. It may be text or a number.