[F] getUnionAsEnum
function getUnionAsEnum(union): [undefined | UnionEnum, 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
| Parameter | Type | Description |
|---|---|---|
union | Union | Union to try to convert |
Returns
[undefined | UnionEnum, readonly Diagnostic[]]
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