typescriptvue.jstypescript-eslintvue-directives

Vue 3 custom directive with modifier type check


How can I create a Vue 3 custom directive and have TypeScript throw a compile-time error if a modifier supplied to this directive is not a known value.

For example:

type MyCustomDirectiveKnownModifiers = 'foo' | 'bar';
<div v-my-custom-directive.foo /> // OK
<div v-my-custom-directive.bar /> // OK
<div v-my-custom-directive.baz /> // TSError: ...

I've tried augmenting the Vue's DirectiveBinding type, but no luck.


Solution

  • I don't think it's possible using a modifier, however you can do something similar with a directive value:

    import type { ObjectDirective } from "vue";
    
    type PossibleParams = "foo" | "bar";
    
    const vTypedDirective: ObjectDirective<any, PossibleParams> = {
      mounted: (el: any) => el.focus(),
    };
    
    
    <div v-typed-directive="'bar'" /> // OK
    <div v-typed-directive="'baz'" /> // TS error