首页 > 解决方案 > TypeScript 自引用

问题描述

我有一个 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:类型“ComponentOptions、DefaultMethods、DefaultComputed、PropsDefinition >、Record...>>”上不存在属性“?constants”。

截屏

标签: typescriptvue.jsphpstorm

解决方案


@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


推荐阅读