Closed ehaynes99 closed 7 months ago
@ehaynes99 Hi, try the following
import { Type, TUnion, TLiteral } from '@sinclair/typebox'
export type TLiteralUnion<T extends string[], Acc extends TLiteral[] = []> =
T extends [infer L extends string, ...infer R extends string[]]
? TLiteralUnion<R, [...Acc, TLiteral<L>]>
: TUnion<Acc>
function LiteralUnion<T extends string[]>(values: readonly [...T]): TLiteralUnion<T> {
return Type.Union(values.map(value => Type.Literal(value))) as never
}
// ...
const V = ['first', 'second', 'third'] as const
const T = LiteralUnion(V)
Hope this helps S
It does indeed. Thanks, you're the best!
I've been trying -- unsuccessfully -- to come up with a function to create a
TUnion
using a const array (or a TS 5.x "const parameter" like<const T extends ReadonlyArray<string | number | boolean>>
). E.g.I thought it would be straightforward:
However, this doesn't satisfy the generics for
TUnion
I tried approaching from the other direction:
But would have to use an unsafe type to actually create it, e.g.:
This works, but feels rather ugly, as TypeBox doesn't really have a native equivalent. Any ideas?