【问题标题】:TypeScript self referenceTypeScript 自引用
【发布时间】:2021-03-09 07:43:40
【问题描述】:

我有一个 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”。

【问题讨论】:

  • 你的界面没有$options属性
  • @captain-yossarian,$options 是 ComponentOptions 类型的标准 vue 组件属性。在这个道具中将合并所有在 vue 组件对象中声明的未记录的道具(如“常量”或任何其他未保留的名称)
  • 请查看官方文档 (vuejs.org/v2/guide/…) - 它对您有用吗?
  • 编译错误,不知道和PHPstorm有什么关系

标签: typescript vue.js phpstorm


【解决方案1】:

@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

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 2018-01-16
    • 2016-11-15
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多