Skip to content

Enum From Object Literal Keys #839

Discussion options

You must be logged in to vote

@sbking @danielyogel

I think I understand the problem better now. Thanks.

Here's how I would solve it:

function zodEnumFromObjKeys<K extends string> ( obj: Record<K, any> ): z.ZodEnum<[ K, ...K[] ]> {
    const [ firstKey, ...otherKeys ] = Object.keys( obj ) as K[]
    return z.enum( [ firstKey, ...otherKeys ] )
}
type Post = {
    createdAt: number
    comments: string[]
}

const ordering = {
    new: ( a: Post, b: Post ) => b.createdAt - a.createdAt,
    old: ( a: Post, b: Post ) => a.createdAt - b.createdAt,
    popular: ( a: Post, b: Post ) => b.comments.length - a.comments.length,
} as const
// } satisfies Record<string, (a: Post, b: Post) => number>
// you could use the new `satisfi…

Replies: 5 comments 10 replies

Comment options

You must be logged in to vote
0 replies
Comment options

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

@danielyogel
Comment options

@JacobWeisenburger
Comment options

@sbking
Comment options

Comment options

You must be logged in to vote
6 replies
@bennik88
Comment options

@feychenie
Comment options

@SrBrahma
Comment options

@krisgrm
Comment options

@CanRau
Comment options

Answer selected by JacobWeisenburger
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
10 participants