Skip to content

Commit 7761526

Browse files
committed
docs: add typing support documentation for plugins
1 parent c707b2b commit 7761526

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/guide/reusability/plugins.md

+2
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,5 @@ export default {
139139
### Bundle for NPM
140140

141141
If you further want to build and publish your plugin for others to use, see [Vite's section on Library Mode](https://vitejs.dev/guide/build.html#library-mode).
142+
143+
See also: [Typing Plugins](/guide/typescript/composition-api#typing-plugins) <sup class="vt-badge ts" />

src/guide/typescript/composition-api.md

+50
Original file line numberDiff line numberDiff line change
@@ -476,3 +476,53 @@ const openModal = () => {
476476
```
477477

478478
Note that with `@vue/language-tools` 2.1+, static template refs' types can be automatically inferred and the above is only needed in edge cases.
479+
480+
## Typing Plugins {#typing-plugins}
481+
482+
Vue provides built-in type support for plugins. There are two types of plugins: object plugins and function plugins. The type of the plugin will be automatically inferred by `app.use()`:
483+
484+
```ts
485+
import { type App, createApp } from 'vue'
486+
487+
const app = createApp({})
488+
489+
const objectPlugin = {
490+
install(app: App, options1: { foo: number }, options2: { bar: number }) {
491+
// ...
492+
}
493+
}
494+
app.use(objectPlugin, { foo: 1 }, { bar: 2 })
495+
app.use(objectPlugin, { foo: 1 }) // => TS Error: Expected 2 arguments, but got 1.
496+
497+
const functionPlugin = (app: App, options1: { foo: number }) => {
498+
// ...
499+
}
500+
app.use(functionPlugin, { foo: 1 })
501+
```
502+
503+
Vue provides a `Plugin` utility type to represent both plugin types. You can use it to define your plugin with proper type checking:
504+
505+
```ts
506+
import { type Plugin, createApp } from 'vue'
507+
508+
const app = createApp({})
509+
510+
// Define plugin with array type parameters
511+
const objectPlugin: Plugin<
512+
[options1: { foo: number }, options2?: { bar: number }]
513+
> = {
514+
install(app, options1, options2) {
515+
// ...
516+
}
517+
}
518+
app.use(objectPlugin, { foo: 1 })
519+
520+
// Optional parameters
521+
const functionPlugin: Plugin<[options?: { foo: number }]> = (
522+
app,
523+
options
524+
) => {
525+
// ...
526+
}
527+
app.use(functionPlugin)
528+
```

0 commit comments

Comments
 (0)