Composition-api: docs: how to extend `Context` in Typescript

Created on 28 Jul 2020  路  3Comments  路  Source: nuxt-community/composition-api

馃摎 Is your documentation request related to a problem? Please describe.

I was trying to extend the Context interface in a library by using the example in the Nuxt Typescript documentation:

declare module '@nuxt/types' {
  interface Context {
    $myInjectedFunction(message: string): void
  }
}

So I can type the object returned by useContext, but I can't figure out a working combination, it seems to completely override the Context interface. So far I tried:

  • Adding an extra file nuxt/index.d.ts in the library and add it in the tsconfig.json file -> overwrite the Context interface instead of extending it, doesn't even extend useContext
  • Adding a global.d.ts file where I extend the Context myself -> same as above
  • Adding it to the library directly -> works but would fail if the user is not using Nuxt

Is there a way to add this so it works both for Nuxt users and Vue users?

馃攳 Where should you find it?

I think this would be useful for anybody creating Composition API plugins that work with SSR

鈩癸笍 Additional context

For reference, this is the library I'm trying to add it to: https://github.com/posva/mande

documentation

Most helpful comment

That's a good idea. I've created a PR in the TS repo - your thoughts welcome.

All 3 comments

@posva If you add nuxt/index.d.ts, just make sure to import the module you are extending, like so:

import '@nuxt/types'

declare module '@nuxt/types' {
  interface Context {
    $myInjectedFunction(message: string): void;
  }
}

Hope this helps - and mande looks great!

Damn, I was just missing that import. Is this something you want to include in documentation in a new page or maybe you have a different idea?

That's a good idea. I've created a PR in the TS repo - your thoughts welcome.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MartinMalinda picture MartinMalinda  路  7Comments

tcastelly picture tcastelly  路  7Comments

resessh picture resessh  路  5Comments

Quineone picture Quineone  路  5Comments

lewebsimple picture lewebsimple  路  7Comments