[F] getUnionAsEnum
function getUnionAsEnum(union): [UnionEnum | undefined, readonly Diagnostic[]];Tries to convert a union into an enum. If the union only contains the same type of literal options with optionally the base scalar to mark extensibility we can represent this union as an enum of that type.
Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
union | Union | Union to try to convert |
Returns
Section titled “Returns”[UnionEnum | undefined, readonly Diagnostic[]]
Example
Section titled “Example”Simple closed string enum
union PetKind { "cat", "dog" }const [enum, diagnostics] = getUnionAsEnum(union);enum.open === falseenum.open.members.get("cat") // { value: "cat", variant: ... }enum.open.members.get("dog") // { value: "dog", variant: ... }Simple open string enum
union PetKind { Cat: "cat", Dog: "dog", string }const [enum, diagnostics] = getUnionAsEnum(union);enum.open === trueenum.open.members.get("Cat") // { value: "cat", variant: ... }enum.open.members.get("Dog") // { value: "dog", variant: ... }Invalid case
union PetKind { Cat: "cat", Dog: 123, string }const [enum, diagnostics] = getUnionAsEnum(union);enum === undefineddiagnostics.length === 1