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.
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.
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.
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.