【问题标题】:How to override a TypeScript interface without extending?如何在不扩展的情况下覆盖 TypeScript 接口?
【发布时间】:2018-07-27 17:23:02
【问题描述】:

我正在使用一个库 (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;

【问题讨论】:

  • 少用// @ts-ignore,不能用。
  • 嗯,这很蹩脚。 :/ 是时候为 TS 3.x 提出功能请求了。
  • @Ohgodwhy 见我上面的编辑。

标签: typescript vue.js


【解决方案1】:

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

使用 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;
  }
}

现在,您可以在任何组件中扩展 mixin,并调用 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 做同样的事情)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 2016-07-06
    • 2019-12-31
    相关资源
    最近更新 更多