如何在不扩展的情况下覆盖TypeScript接口?

时间:2018-07-27 17:23:02

标签: typescript vue.js

我正在使用一个库(vue-i18n),该库在其types/index.d.ts文件中(为简洁起见而对其进行了定义):

declare class VueI18n {
  t(key: VueI18n.Path, values?: VueI18n.Values): VueI18n.TranslateResult;
  t(key: VueI18n.Path, locale: VueI18n.Locale, values?: VueI18n.Values): VueI18n.TranslateResult;
}

declare module 'vue/types/vue' {
  interface Vue {
    $t: typeof VueI18n.prototype.t;
  }
}

我不喜欢t函数返回一个TranslateResult并想覆盖它(就位,而不是通过扩展名),以便它返回一个字符串。

我尝试在项目中创建自己的declarations.d.ts文件:

import VueI18n from 'vue-i18n';

declare module 'vue/types/vue' {
  interface Vue {
    $t(key: VueI18n.Path, values?: VueI18n.Values): string;
    $t(
      key: VueI18n.Path,
      locale: VueI18n.Locale,
      values?: VueI18n.Values
    ): string;
  }
}

但是不喜欢这样。

[ts] Duplicate identifier '$t'.

我需要进行就地覆盖,换句话说,在不扩展到新接口的情况下替换类型。我该怎么做?

编辑:

好的,这似乎不可能。有什么方法可以减少在这里使用as string的重复性吗?

this.msg = this.$t('blah') as string;
this.str2 = this.$t('thisToo') as string;
this.strX = this.$t('another') as string;
this.g = this.$t('test') as string;

1 个答案:

答案 0 :(得分:0)

  

好的,这似乎不可能。有什么方法可以减少在这里用作字符串的重复性吗?

使用mixin代理$ t

test-i18n.mixin

import {Vue, Component } from 'vue-property-decorator';

@Component
export default class LangMixin extends Vue {

  public t(key: string, params?: string[]) {
    return this.$t(key, params) as string;
  }
}

现在,您可以在任何组件中扩展混合,并调用this.t而不是this.$t:无需在每次调用中强制转换$t

<template>
  <p>{{someStringProperty}}</p>
</template>

<script lang="ts">
import {Mixins, Component} from 'vue-property-decorator';
import langMixin from './test-i18n.mixin';

@Component
export default class LangTest extends Mixins(langMixin) {

  get someStringProperty(): string {
    return this.t('global.last-name');
  }
}
</script>

我在这里使用vue类组件,但这也可以与Vue.extend一起使用。 但是,如果您使用mixins,我真的建议您改用类组件api,否则您将失去很多智能感知/类型帮助

(当然,您应该对$tc执行相同的操作)。

相关问题