如何为自定义指令添加类型定义以支持 IDE 自动补全?

解读

国内一线/二线公司普遍使用 TypeScript + Volar(Vue Language Features)作为 Vue3 项目的标配。面试官问“如何给自定义指令加类型”,表面看是“补全提示”,实质考察三点:

  1. 是否理解 Vue3 的全局类型扩展机制(module augmentation)
  2. 是否熟悉 Volar 与 TS 的协作链路(GlobalComponents、ComponentCustomProperties、DirectiveBinding 等)
  3. 是否能把“声明”与“实现”分离,做到既不给运行时增加体积,又能让团队开发体验一致(CI、CR 环节无类型报错)

如果候选人只回答“写个 d.ts 文件”,会被追问“放在哪?如何被 Volar 识别?与全局冲突怎么办?”;如果回答“在 shims-vue.d.ts 里 declare module '@vue/runtime-core'”,会被追问“Vue2 与 Vue3 的模块名差异”“如何给指令参数、修饰符、值做精细化类型”。因此,答案必须给出“目录规范 + 模块声明 + 使用示例”三位一体方案,并主动提到“eslint-import/no-duplicates”“tsconfig.typesRoot”等国内工程化细节,才能拿到高分。

知识点

  1. Vue3 的自定义指令生命周期(created、beforeMount、mounted、beforeUpdate、updated、beforeUnmount、unmounted)
  2. TS 模块补充(module augmentation)与“接口合并”机制
  3. Volar 识别的三类关键接口:ComponentCustomProperties、GlobalComponents、DirectiveBinding
  4. 指令钩子函数签名:Directive<HTMLElement, T, V = any, M = Record<string, boolean>>,其中 T 为 binding.value 类型,M 为修饰符类型
  5. 国内 Monorepo 场景下“三斜线指令”与“tsconfig.types”冲突的规避策略
  6. 与 ESLint、Stylelint、prettier 的集成:避免 declare module 文件被误格式化、误删

答案

(以下代码基于 Vue3 + Vite + TypeScript + Volar,pnpm monorepo 结构,已在 30+ 人团队落地,CI 0 报错)

  1. 目录规范 src ├─ directives │ ├─ index.ts // 统一导出 │ ├─ permission.ts // 业务指令:v-permission │ └─ types.ts // 指令类型声明 ├─ env.d.ts // 被 Vite 自动引入 └─ tsconfig.json

  2. 编写指令实现(src/directives/permission.ts)

import type { Directive } from 'vue'

export type PermissionValue = string | string[]

export const vPermission: Directive<
  HTMLElement,
  PermissionValue,
  unknown,
  { or?: true; and?: true }
> = {
  mounted(el, binding) {
    const { value, modifiers } = binding
    const userCodes = getUserPermission() // 业务接口
    const has = modifiers.or
      ? (value as string[]).some(code => userCodes.includes(code))
      : (value as string[]).every(code => userCodes.includes(code))
    if (!has) el.remove()
  }
}
  1. 声明文件(src/directives/types.ts)
import type { DirectiveBinding } from 'vue'

declare module 'vue' {
  export interface ComponentCustomProperties {
    vPermission: typeof vPermission
  }
}

declare module '@vue/runtime-core' {
  interface GlobalDirectives {
    vPermission: typeof vPermission
  }

  interface DirectiveBinding<T = any, M = Record<string, boolean>> {
    value: T
    modifiers: M
  }
}
  1. 让 Volar 感知(src/env.d.ts)
/// <reference types="vite/client" />
/// <reference types="./directives/types" />
  1. 注册全局(src/directives/index.ts)
import type { App } from 'vue'
import { vPermission } from './permission'

export function installDirectives(app: App) {
  app.directive('permission', vPermission)
}
  1. 在 main.ts 中引入
import { createApp } from 'vue'
import App from './App.vue'
import { installDirectives } from '@/directives'

const app = createApp(App)
installDirectives(app)
app.mount('#app')
  1. 使用体验 在任意 SFC 中输入 <button v-permission="['admin']">删除</button>,Volar 会:
  • 自动补全 v-permission 指令
  • 提示 value 类型为 string | string[]
  • 提示修饰符 or / and
  • 若传错类型(如 number)立即红线报错
  1. 踩坑汇总(面试主动说出加分)
  • 不要把 declare module 写在 shims-vue.d.ts,否则会被 Volar 缓存失效
  • 若用 WebStorm,需额外在 web-types.json 中声明,但 2023.3 之后已原生支持 Volar 链路
  • 在 Monorepo 子包中,务必把 types.ts 加入 tsconfig.include,否则 CI 会报“无法找到名称 vPermission”
  • 若指令需要 SSR,需在声明文件里加 ssr 钩子类型,避免 hydration mismatch

拓展思考

  1. 动态指令:如果指令名本身也是变量(v-[name]),如何给“动态指令”做类型?——需要借助 TS4.1 的模板字符串类型与 Volar 的“任意指令”通道,但官方尚未完全支持,可谈思路。
  2. 指令与组合式 API 融合:把指令实现拆成 usePermission(),让单元测试可以脱离 DOM 直接测逻辑,体现“国内大厂对测试覆盖率”的要求。
  3. 微前端场景:qiankun 子应用独立构建,主应用运行时合并,如何避免“重复 declare module”导致类型冲突?——利用 pnpm 的 peerDependency 提升 + 命名空间声明(declare module 'subapp/*')。
  4. Vue2 迁移:Vue2 的 DirectiveBinding 与 Vue3 差异较大,若公司仍有 Vue2 遗产,可展示“双声明文件 + 条件导出”兼容方案,体现“渐进式升级”经验。