ndelvalle / v-click-outside

🔲 Vue directive to react on clicks outside an element without stopping the event propagation
MIT License
967 stars 88 forks source link

TypeScript support #667

Open Matix-Media opened 1 year ago

Matix-Media commented 1 year ago

Please add typescript support.

githuib commented 4 months ago

I've added a d.ts file to a project I'm working on to get type checking (both in programmatic and v-click-outside usage). I put it in vendor/types/click-outside-vue3/index.d.ts but I don't think the path matters much, as long as the compiler can find it (normally by adding it to the "include" field in tsconfig.json).

declare module 'click-outside-vue3' {
  import { App, Directive } from 'vue';

  type Handler = (event: Event) => void;
  interface Params {
    handler: Handler;
    middleware?: (event: Event) => boolean; // default: (event) => true
    events?: string[]; // default: if touch screen: ["touchstart"] | otherwise: ["click"]
    isActive?: boolean; // default: true
    detectIframe?: boolean; // default: true
    capture?: boolean; // default: false
  }
  type ClickOutside = Directive<HTMLElement, Handler | Params>;

  declare const plugin: {
    install: (Vue: App) => void;
    directive: ClickOutside;
  };

  /**
   * Adds type checking when the module is imported, for example:
   *
   * import vClickOutside from "click-outside-vue3";
   *
   * // --- When creating the Vue app ---
   * ...
   * app.use(vClickOutside)
   *
   * // --- In a component ---
   * ...
   * export default {
   *   directives: {
   *     clickOutside: vClickOutside.directive,
   *   },
   *   ...
   * };
   */
  export default plugin;

  /**
   * Adds type checking to the `v-click-outside` attribute
   * when used in .vue files, for example:
   *
   * <template>
   *   <div v-click-outside="onClickOutside"></div>
   * </template>
   */
  declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
      vClickOutside: ClickOutside;
    }
  }
}

It seems to work fine for our use case, but feel free to give me any feedback if something could be improved or I made some mistake etc. :)

Might be interesting to add to this package as well, but I leave that up to the maintainer.