Skip to content

Function to create a union of literal dynamically #2790

Discussion options

You must be logged in to vote

Is this what you are looking for?

function unionOfLiterals<T extends string | number> ( constants: readonly T[] ) {
    const literals = constants.map(
        x => z.literal( x )
    ) as unknown as readonly [ z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[] ]
    return z.union( literals )
}

const MY_CONSTANTS = [ 'a', 'b', 1 ] as const
const unionType = unionOfLiterals( MY_CONSTANTS )
type UnionType = z.infer<typeof unionType>
// type UnionType = "a" | "b" | 1

console.log( unionType.parse( 'a' ) ) // a
console.log( unionType.parse( 'b' ) ) // b
console.log( unionType.parse( 1 ) ) // 1
console.log( unionType.safeParse( 'foo' ).success ) // false

If you found my answer satisfacto…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@william0bra
Comment options

@JacobWeisenburger
Comment options

@william0bra
Comment options

@ImLunaHey
Comment options

Answer selected by JacobWeisenburger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #2789 on September 25, 2023 00:01.