本文介绍了如何让 TypeScript “知道"将公共实例属性($locale)添加到 Vue 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Vue 应用程序中使用 v-localize 并且我正在迁移到打字稿.v-localize 像这样添加到应用程序中:

I'm using v-localize in my Vue app and I'm migrating to TypeScript. v-localize is added to the app like this:

//...
const Localize = require('v-localize'); // was import before migration to TS
import { locales } from './localize';

//...
Vue.use(Localize);

new Vue({
  el: '#app',
  store,
  localize: locales,
  render: (h: Function) => h(App) //# h: Vue.CreateElement? , => Vue.VNode?
});

带来

错误:(13, 3) TS2769:没有与此调用匹配的过载.[....]

而我目前用它来压制

} as any);

在最后一行;在脚本中(而不是在模板中)它是这样使用的:

in the last line; and in scripts (as opposed to in templates) it is used like this:

const myLocalizedString = this.$locale({i: 'scopeName.stringName'})

其中 $locale

未解析的函数或方法$locale()

再说一次,我可以这样压制它:

Again, I can suppress it like this:

(this as any).$locale({i: 'scopeName.stringName'})

但我想知道是否有更一致(且更简洁)的方法.如何让 TypeScript 知道 Vue 配置的新字段和 $locale 方法?

but I wonder if there's a more consistent (and less verbose) approach. How do I make TypeScript aware of both new field of Vue config and of the $locale method?

推荐答案

这是我的部分解决方案:

Here's my partial solution:

  • 使用 import Localize from 'v-localize' 而不是 const Localize = require('v-localize') 我添加了一个文件 v-localize.d.ts 像这样:

  • to use import Localize from 'v-localize' instead of const Localize = require('v-localize') I added a file v-localize.d.ts like this:

declare module 'v-localize' {
    export default function Localize (): any;
}

当然这不是一个专门的打字,但对于这个特定的任务来说已经足够了

surely this is not a dedicated typing but is good enough for this particular task

为了访问组件中的 .$locale 并获取其参数的类型建议,我引入了另一个文件 v-localize-vue.d.ts(模块扩充示例)::>

to access .$locale in components and get type suggestions of its argument, I've introduced another file v-localize-vue.d.ts (module augmentation example):

import Vue from 'vue'

type localeArgument = {
    i: string
}

declare module 'vue/types/vue' {
    interface Vue {
        $locale: (a: localeArgument) => string
    }
}

  • 从Vue选项中删除});位,我已经添加到v-localize-vue.d.ts(在符合相同的文档):

  • to remove the } as any); bit from the Vue options, I've added to v-localize-vue.d.ts (in accord with the same doc):

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

  • 我将解决方案称为部分",因为我在第一和第三位使用了 any 并且我还没有挖掘我的 localeArgument 类型是否准确(也许是对象可以包含其他字段,i 不是必需的).

    I call the solution "partial" since I use any in the first and the third bit and I haven't digged whether my localeArgument type is accurate (perhaps the object can contain other fields and i is not required).

    这篇关于如何让 TypeScript “知道"将公共实例属性($locale)添加到 Vue 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-24 15:34