diff --git a/src/guide/reusability/custom-directives.md b/src/guide/reusability/custom-directives.md index a8b51935f7..3325b704d0 100644 --- a/src/guide/reusability/custom-directives.md +++ b/src/guide/reusability/custom-directives.md @@ -110,6 +110,10 @@ app.directive('highlight', { }) ``` +It is possible to type global custom directives by extending the `ComponentCustomProperties` interface from `vue` + +More Details: [Typing Custom Global Directives](/guide/typescript/composition-api#typing-global-custom-directives) + ## When to use custom directives {#when-to-use} Custom directives should only be used when the desired functionality can only be achieved via direct DOM manipulation. diff --git a/src/guide/typescript/composition-api.md b/src/guide/typescript/composition-api.md index 3035afd5dc..4a7376803b 100644 --- a/src/guide/typescript/composition-api.md +++ b/src/guide/typescript/composition-api.md @@ -468,7 +468,8 @@ import { useTemplateRef } from 'vue' import MyGenericModal from './MyGenericModal.vue' import type { ComponentExposed } from 'vue-component-type-helpers' -const modal = useTemplateRef>('modal') +const modal = + useTemplateRef>('modal') const openModal = () => { modal.value?.open('newValue') @@ -477,3 +478,41 @@ const openModal = () => { ``` 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. + +## Typing Global Custom Directives {#typing-global-custom-directives} + +In order to get type hints and type checking for global custom directives declared with `app.directive()`, you can extend `ComponentCustomProperties` + +```ts [src/directives/highlight.ts] +import type { Directive } from 'vue' + +export type HighlightDirective = Directive + +declare module 'vue' { + export interface ComponentCustomProperties { + // prefix with v (v-highlight) + vHighlight: HighlightDirective + } +} + +export default { + mounted: (el, binding) => { + el.style.backgroundColor = binding.value + } +} satisfies HighlightDirective +``` + +```ts [main.ts] +import highlight from './directives/highlight' +// ...other code +const app = createApp(App) +app.directive('highlight', highlight) +``` + +Usage in component + +```vue [App.vue] + +``` diff --git a/src/guide/typescript/options-api.md b/src/guide/typescript/options-api.md index 0532d3a39a..0bd343884b 100644 --- a/src/guide/typescript/options-api.md +++ b/src/guide/typescript/options-api.md @@ -291,3 +291,7 @@ The placement of this augmentation is subject to the [same restrictions](#type-a See also: - [TypeScript unit tests for component type extensions](https://github.com/vuejs/core/blob/main/packages-private/dts-test/componentTypeExtensions.test-d.tsx) + +## Typing Global Custom Directives {#typing-global-custom-directives} + +See: [Typing Custom Global Directives](/guide/typescript/composition-api#typing-global-custom-directives)