You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
`Variant`s (alternatively known as "sum types",
"discriminated unions", or "tagged unions") are a
way to define a type that can be one of several
different types, but only one at a time.
This is useful for representing data that can
take on multiple forms, such as for JSON data
that can be one of several different types
(e.g. a string, number, object, array, etc.).
* const bad1: ColorVariant = { rgb: new Rgb({ r: Field(255), g: Field(10), b: Field(0) }), named: CircuitString.fromString("pink") }; // This will cause a type error because both keys are present.
43
+
* const bad2: ColorVariant = { }; // This will also cause a type error, there aren't any keys.
44
+
* const bad3: ColorVariant = { blarg: Field(13n) }; // This will also cause a type error, since `blarg` is not a key in `ColorVariant`.
45
+
* const bad4: ColorVariant = { rgb: CircuitString.fromString("pink") }; // This will also cause a type error, since `rgb` must be an instance of `Rgb`.
46
+
* ```
47
+
*
48
+
*/
49
+
typeExactlyOne<T>=AtMostOne<T>&AtLeastOne<T>
50
+
51
+
// Helper to get the single key from an ExactlyOne type
52
+
functiongetKey<T>(value: ExactlyOne<T>): keyofT{
53
+
constkeys=Object.keys(value);
54
+
if(keys.length!==1){
55
+
thrownewError("Invalid variant: expected exactly one key, got: "+keys.length);
56
+
}
57
+
returnkeys[0]askeyofT;
58
+
}
59
+
60
+
/**
61
+
* Creates a variant type that can hold exactly one of the provided types.
62
+
*
63
+
* @param variants - An object where each key is a variant name and the value is the type of that variant.
64
+
*
65
+
* @returns A class that represents the variant type, with methods for serialization, deserialization, and other operations.
66
+
*
67
+
* @remarks sizeInFields returns the maximum size of the fields required to represent any of the variants _plus one for the index_.
68
+
*
69
+
* @example
70
+
* ```typescript
71
+
* // Define a struct for RGB colors.
72
+
* class Rgb extends Struct({
73
+
* t: Field,
74
+
* g: Field,
75
+
* b: Field,
76
+
* }) {}
77
+
*
78
+
* // Define a variant type that can be either an RGB color or a named color.
79
+
* class Color extends Variant({
80
+
* rgb: Rgb,
81
+
* named: CircuitString,
82
+
* }) {}
83
+
*
84
+
* // Each variant is represented by a single key-value pair.
0 commit comments