-
Beta Was this translation helpful? Give feedback.
Answered by
franky47
Jan 8, 2024
Replies: 1 comment 2 replies
-
Looks like what you are trying to do is make sure a particular string conforms to a set of literals, like 'A' or 'B'. For this, I would recommend updating your custom parser to check at runtime that the incoming query string value actually matches those literals, as blindly type-casting it breaks type-safety assumptions. const letters = ['A', 'B'] as const
type Letter = typeof letters[number] // 'A' | 'B'
function isLetter(input: string): input is Letter {
// Ok to type-cast here because we're narrowing
return letters.includes(input as Letter)
}
const letterParser = createParser({
parse: query => {
if (!isLetter(query)) {
return null
}
return query
},
serialize: value => value
}) Or, using a schema library like Zod: import { createParser } from 'nuqs'
import { z } from 'zod'
const letterSchema = z.union([z.literal('A'), z.literal('B')])
const letterParser = createParser({
parse: query => {
const result = letterSchema.safeParse(query)
if (result.success) {
return result.data
} else {
return null
}
},
serialize: value => value
}) |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
franky47
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
parseArrayOf
will return an array of the type returned by the item parser passed in argument, so if you pass itparseAsString
, it will return an array of strings.Looks like what you are trying to do is make sure a particular string conforms to a set of literals, like 'A' or 'B'. For this, I would recommend updating your custom parser to check at runtime that the incoming query string value actually matches those literals, as blindly type-casting it breaks type-safety assumptions.