Vue 3 custom directive with modifier type check

643 Views Asked by At

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.

1

There are 1 best solutions below

2
Florent Bouisset On BEST ANSWER

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