Skip to content

RTK Query: How to add type-safe runtime validation for server responses without writing code on a per-endpoint basis? #2576

Answered by phryneas
jimmycuadra asked this question in Q&A
Discussion options

You must be logged in to vote

Your request reads to me as "how to get runtime validation with only types" - and that cannot be possible.

But of course you can write yourself a wrapper to make it nicer to read:

export type TypeOf<T extends ZodType<any, any, any>> = T["_output"];

function validate<T extends ZodType<any, any, any>>(schema: T): TypeOf<T> {
  return response => schema.parse(response)
}

// in your endpoint

  endpoints: (build) => ({
    getPost: build.query<Post, string>({
      query: (id) => `posts/${id}`,
      transformResponse: validate(Post)
    }),
  }),

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@jimmycuadra
Comment options

@phryneas
Comment options

@jimmycuadra
Comment options

@phryneas
Comment options

@jimmycuadra
Comment options

Answer selected by jimmycuadra
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