Skip to content

Union and Intersection

Union and intersection types in Filtrera provide powerful ways to define and work with complex data structures. This reference guide provides a detailed specification of union and intersection types, their syntax, and usage for users already familiar with the concept.

Union types allow you to define a variable that can hold values of multiple types, while intersection types allow you to define a variable that must satisfy multiple type constraints simultaneously. These types enhance the flexibility and expressiveness of Filtrera’s type system.

Union Types

Union types are defined using the pipe (|) symbol. A union type allows a variable to hold a value that can be any one of the specified types.

Syntax

<type1> | <type2> | <type3>

Example

let unionType: text | number | boolean

In this example, unionType can hold a value that is either text, number, or boolean.

Practical Usage

let processValue = (v: text | number) =>
from v match
x: text |> 'Text: {x}'
x: number |> 'Number: {x}'
let result1 = processValue('Hello')
let result2 = processValue(42)
from result1
from result2

In this example, processValue processes a value that can be either text or number and returns a corresponding string.

Intersection Types

Intersection types are defined using the ampersand (&) symbol. An intersection type requires a variable to satisfy multiple type constraints simultaneously.

Syntax

<type1> & <type2> & <type3>

Example

let intersectionType: text & not ''

In this example, intersectionType can be any text except empty.

Combining Union and Intersection Types

Union and intersection types can be combined to create even more flexible and powerful type definitions.

Example

let combinedType: { name: text & not '', age: number } | boolean
let processCombinedType = (input: combinedType) =>
from input match
x: { name: text, age: number } |> 'Name: {x.name}, Age: {x.age}'
x: boolean |> 'Boolean: {x}'
let result1 = processCombinedType({ name = 'Alice', age = 30 })
let result2 = processCombinedType(true)
from result1
from result2

In this example, combinedType can be either an object with name and age fields or a boolean. The processCombinedType function processes the input accordingly and returns a corresponding string.

Summary

Union and intersection types in Filtrera provide powerful mechanisms for defining complex and flexible data structures. By understanding their syntax and usage, including how to define and combine them, you can enhance the expressiveness and robustness of your Filtrera programs. Union types allow variables to hold values of multiple types, while intersection types require variables to satisfy multiple type constraints simultaneously, enabling you to create more precise and flexible type definitions.