打字稿自参考

问题描述

我有一个 Vue 插件,它允许以快捷方式访问 .vue 文件模板中的常量对象:

<template>
    <span>{{ $consts.HELLO }}</span>
</template>

export default {
    constants: {HELLO: 'hello there!'},};

$consts 这里是指向 $options.constants链接

如何在 TypeScript 中描述此功能?我的版本是:

declare module 'vue/types/vue' {
    interface Vue {
        readonly constants?: object
        readonly $consts: Vue['$options']['?constants'] // ???
    }
}

但是 TypeScript 向我展示了这个错误

TS2339:属性“?constants”在类型“ComponentOptions、DefaultMethods、DefaultComputed、PropsDeFinition>、Record...>>”上不存在。

screenshot

解决方法

@lena 分享了这个指向 Vue 官方说明的链接: https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins

就我而言,我需要像这样扩展 ComponentOptions

declare module 'vue/types/options' {
  interface ComponentOptions<V extends Vue> {
    constants?: {}
  }
}

并从这一行中删除问号

readonly $consts: Vue['$options']['?constants']

所以现在在 phpStorm *.vue 文件中,IDE 不会警告 Unresolved variable or type $consts