7 ms·
Union types seem a bit wacky, are they typically used over function overloading or generics?
by jb_s 5y ago
Union types seem a bit wacky, are they typically used over function overloading or generics?
- exdsq 5y agoThe most common thing to use them for in TS is to acknowledge a value could be of type null or undefined. Let’s you then check you’re handling them correctly.
- AgentME 5y agoUnion types let you accomplish very similar things to what you can do in languages that support Enums with associated values, like Rust. (See https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html for examples of what that looks like. There's no great direct comparison in Java, because Java Enums don't support associated values like this; the closest Java pattern would involve making multiple classes that each extend an interface or abstract class.)
- Zababa 5y agoAn example of union types: many API in JS accept HTTP verbs as strings. With union types, you can say something like: type HttpVerb = "GET" | "POST" | "PUT" | "DELETE"; But you can also do more complex stuff: type User = {name: string; password: strings} | OAuthID; By themselves they aren't hard to understand or use. As an aside, compared to sum types, you don't have to define them before using them: a function can return number | null while in language with sum types you usually define option first and then return option<number>.
- arxanas 5y agoYou might find my blog post on some of the uses interesting: https://blog.waleedkhan.name/union-vs-sum-types/ https://blog.waleedkhan.name/union-vs-sum-types/ In a language like TypeScript, they can be used for function overloading since there is no runtime dispatch based on argument type. But usually they're used as sum types in the same way as e.g. Rust enums. Typescript supports so-called "singleton types", in which a given type is inhabited by exactly one value. This lets you do things like specify not just `string` but specific values like `"foo" | "bar"` as a type. In these cases, I often use them in combination with Typescript's "mapped types", which let you index into a map with a certain type and get another type out. This can be useful for things like RPC calls, where the type of the output depends on the type of the input.
- jb_s 5y ago>since there is no runtime dispatch based on argument type Ah, this answers my question I guess. Thanks for the info. I'm about to start a new job doing Typescript stuff so I am going to be deep diving into the language to get my head around it, so this helps a lot :-)