Skip to content

How to type parseAsArrayOf #445

Closed Answered by franky47
giannif asked this question in Q&A
Jan 8, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

parseArrayOf will return an array of the type returned by the item parser passed in argument, so if you pass it parseAsString, 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.

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(

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@giannif
Comment options

@franky47
Comment options

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