Closed adnelson closed 10 months ago
@adnelson there are no options to generate enums.
Would this be desirable? The use case I'm looking at now is the nexus graphql schema library, which can take a JS enum and produce a graphql enum type.
Hypothetically:
[@genType.enum]
type color = [ | `Red | `Blue ];
Or alternatively, via a flag in gentypeconfig
like
{
"gentypeconfig": {
"variantStyle": "enum"
}
}
If this is something you might be interested in, I can try my hand at implementing it.
@adnelson how about starting by exploring the design, then see how that fits.
A couple of first questions:
Up = "UP"
, not identical "UP" = "UP"
. And more in general, only a subset of enums will be representable.I'll circle back on the design, my initial thoughts regarding your Q's:
| [@genType.as "UP"] `Up
)export enum MyEnum {
Foo = "Foo",
Bar = "BAR",
};
tsc
will emit code like this
var MyEnum;
(function (MyEnum) {
MyEnum["Foo"] = "Foo";
MyEnum["Bar"] = "BAR";
})(MyEnum || (MyEnum = {}));
;
Which means that at runtime MyEnum.Foo === "Foo"
.
const myEnumValues = {
Foo: "Foo",
Bar: "BAR",
};
type MyEnum = $Keys<typeof myEnumValues>;
Looks like in TS a value of enum type also has union type, but not the other way round. Not sure why that is the case if the runtime representation is the same.
OK looks like color.Red
is nominally typed, so it's a different type than "Red"
.
Poly variants are structurally typed, so mapping them to a nominal type has a few footguns, e.g. you can't rely on type inference.
E.g. if you export @genType let red = `Red
it won't have type color
.
@adnelson could you explain the use case with nexus graphql a bit more in detail? And whether there are other use cases.
If the use case is worth it, it could be an experimental feature.
Happy to continue the convo if there's still interest? Or we can close this otherwise.
This repository is being archived. If you feel like the issue still relevant, please re-create it in the compiler repo. Thanks!
If I have some code like this:
then gentype will create a binding like
I was looking at the options and I'm not sure if I missed it but is there a way to generate an enum like
?