-
Notifications
You must be signed in to change notification settings - Fork 330
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.
Already on GitHub? Sign in to your account
Cannot generically create type'd union from string literals for an enum #678
Comments
The problem is that In this case also the import * as t from 'io-ts';
const myEnumValues = [
'value_a',
'value_b',
'value_c',
] as const;
export type MyEnumValue = typeof myEnumValues[number];
const [first, second, ...rest] = myEnumValues;
export const tMyEnumValue = t.union([
t.literal(first),
t.literal(second),
...rest.map((value) => t.literal(value))
]); If you want to support less that two elements but at least one you could write your own import * as t from 'io-ts'
import * as NEA from 'fp-ts/NonEmptyArray'
export const relaxedUnion = <A extends NEA.NonEmptyArray<t.Mixed>>(
codecs: A,
name?: string,
): t.Type<t.TypeOf<A[number]>, t.OutputOf<A[number]>> =>
pipe(
codecs,
NEA.matchLeft((head1, tail) =>
pipe(
tail,
A.matchLeft(
() => head1,
(head2, tail2) => t.union([head1, head2, ...tail2], name),
),
),
),
); |
馃悰 Bug report
Current Behavior
I would expect
tMyEnumValue
to be equivalent to the following:However, the explicit string literals work well while the maps do not. I get the following TS compiler error:
Here's a screenshot in VSCode
Expected behavior
t.union(stringsArray.map(t.literal)
compiles and works properly.Reproducible example
See above
Suggested solution(s)
I'm not a deep expert on the
io-ts
library, so I don't yet know how to solve this. I'm happy to learn more tho and contribute a PR if there's someone on the team willing to point me in the right direction.Or perhaps I'm missing something here and there's an obvious way to do what I'm trying to do here.
Your environment
Which versions of io-ts are affected by this issue? Did this work in previous versions of io-ts?
The text was updated successfully, but these errors were encountered: