wobsoriano / trpc-nuxt

End-to-end typesafe APIs in Nuxt applications.
trpc-nuxt.vercel.app
MIT License
687 stars 39 forks source link

How to infer type when passed as prop to a component? #161

Closed charlie-s closed 3 months ago

charlie-s commented 8 months ago

Given this page.vue:

const { data: foo } = await $client.foo.get.useQuery({ id: Number(route.params.id) })
...
<SomeComponent :foo />

what is the recommended approach to inferring the type in SomeComponent?

I tried the following:

server/trpc/routers/index.ts:

import { router } from '../trpc'
import type { inferRouterOutputs } from '@trpc/server'

import { fooRouter } from './foo'

export const appRouter = router({
  foo: fooRouter
})

export type AppRouter = typeof appRouter
export type RouterOutput = inferRouterOutputs

components/SomeComponent.vue:

import { type RouterOutput } from 'server/trpc/routers'
defineProps<{foo: RouterOutput['foo']['get']}>()

but this results in the error A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function..

Before I go deeper down the rabbit hole, I wonder if there's something I couldn't find in the docs that help with this.

Jimmyzm commented 8 months ago

You should pass the AppRouter type to the inferRouterOutputs

export type AppRouter = typeof appRouter
export type RouterOutput = inferRouterOutputs<AppRouter>  <== this line

And you'd better write the code somewhere client side then import.