Narrowing a return type from a generic, discriminated union in TypeScript

Like many good solutions in programming, you achieve this by adding a layer of indirection. Specifically, what we can do here is add a table between action tags (i.e. “Example” and “Another”) and their respective payloads. type ActionPayloadTable = { “Example”: { example: true }, “Another”: { another: true }, } then what we can … Read more

Questions regarding C++ non-POD unions

You’re mostly on your own. A note in the standard explains this (9.5/2): If any non-static data member of a union has a non-trivial default constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move assignment operator (12.8), or destructor (12.4), the corresponding member function of the union must be user-provided or … Read more

Discriminated union in C#

I don’t really like the type-checking and type-casting solutions provided above, so here’s 100% type-safe union which will throw compilation errors if you attempt to use the wrong datatype: using System; namespace Juliet { class Program { static void Main(string[] args) { Union3<int, char, string>[] unions = new Union3<int,char,string>[] { new Union3<int, char, string>.Case1(5), new … Read more