content icon indicating copy to clipboard operation
content copied to clipboard

Type 'IContentDocument | IContentDocument[]' must have a '[Symbol.iterator]()' method that returns an iterator

Open lewsmith opened this issue 4 years ago • 2 comments

I'm getting this typescript error:

Type 'IContentDocument | IContentDocument[]' must have a '[Symbol.iterator]()' method that returns an iterator

When I try to load content using the same code as in the snippets on the nuxt content docs - https://content.nuxtjs.org/snippets

I've got the types setup in my tsconfig.json and the code (using class-based) looks like this:

asyncData: async ({ $content, app, params, error }) => {
    const path = `/${app.i18n.locale}/${params.pathMatch || 'index'}`
    const [document] = await $content({ deep: true })  <--- Document property has the error
      .where({ path })
      .fetch()

    if (!document) {
      return error({ statusCode: 404, message: 'Page not found' })
    }

    return {
      document,
    }
  }

However, if I specify a type on the fetch the error goes away:

asyncData: async ({ $content, app, params, error }) => {
    const path = `/${app.i18n.locale}/${params.pathMatch || 'index'}`
    const [document] = await $content({ deep: true })
      .where({ path })
      .fetch<IContentDocument[]>() <--- Fix

    if (!document) {
      return error({ statusCode: 404, message: 'Page not found' })
    }

    return {
      document,
    }
  },

Is there a way I can remove the need to specify the type on the fetch call?

nuxt-content-err

lewsmith avatar Oct 27 '20 11:10 lewsmith

@lewsmith for me this worked

    const [prev = null, next = null] = (await $content(app.i18n.locale)
      .only(['title', 'slug'])
      .sortBy('createdAt', 'asc')
      .surround(params.slug)
      .fetch()) as Array<IContentDocument>

pablomuro avatar Feb 23 '21 11:02 pablomuro

Can this be considerate as an issue, and is it fixable ? Because adding explicit type declaration at every fetch is a bit annoying...

LoganTann avatar Jul 28 '21 12:07 LoganTann

Since @nuxt/content@v1 will not get any improvement updates. This issue could solve simply by type conversion like described in https://github.com/nuxt/content/issues/604#issuecomment-784136695

farnabaz avatar Dec 12 '22 15:12 farnabaz