Union
Union types for representing TypeScript union types in Kotlin.
TypeScript union types like string | number | boolean are represented using Union classes (U2, U3) in Kotlin.
Usage Examples
Binary Union (U2)
// TypeScript: string | number
val value: Union.U2<String, Number> = Union.U2.ofA("hello")
// or
val value2: Union.U2<String, Number> = Union.U2.ofB(42)
// Check which type it is
if (value.isA()) {
println(value.valueOfA()) // "hello"
}Content copied to clipboard
Ternary Union (U3)
// TypeScript: string | number | boolean
val value: Union.U3<String, Number, Boolean> = Union.U3.ofA("hello")
// or
val value2: Union.U3<String, Number, Boolean> = Union.U3.ofB(42)
val value3: Union.U3<String, Number, Boolean> = Union.U3.ofC(true)Content copied to clipboard
Serialization
Union types are automatically serialized/deserialized when used in AST nodes. The serializer will try each type in order until one succeeds.