Search code examples
typescriptvue.jsvolar

How can I add type hints for my custom global Vue directives?


I can get TypeScript hints if I import or create a directive in a SFC file as follows:

import vFocus from 'my-custom-component-library';

demo with ts hints

Howerver, if I register it globally in main.ts, I cannot get the type hints.

For example:

app.directive('focus', vFocus);

demo without ts hints

So how can I add type hints if I want to globally install it?


Solution

  • According to the vue-language issue 465, currently I can declare the Directives in ComponentCustomProperties for global register directives but it may pollution component global properties.

    // shim-vue.d.ts
    import vFocus from 'my-custom-component-library'
    
    declare module '@vue/runtime-core' {
        export interface ComponentCustomProperties {
            vFocus: typeof vFocus;
        }
    }
    
    export { }