【问题标题】:Extended interface doesn't seem to implement parent members扩展接口似乎没有实现父成员
【发布时间】:2021-02-04 05:25:34
【问题描述】:

我有两个接口

export interface IComponent{
    type: ComponentType;
    name: string;
    isEnabled:boolean;
}

export interface IAudioComponent extends IComponent {
    source: string;
    volume: number;
    loop: boolean;
    playbackRate: number;
}

但是当我像这样在我的 VueComponent 中记录一个 IAudioComponent 时

  data() {
    return {
      _componentGroup: this.componentGroup as IComponentGroup,
      _focussedComponent: this.componentGroup.components[0] as IComponent,
    };
  },
  computed: {
    focussedComponentType() {
      console.log(this.$data._focussedComponent);
      return this.$data._focussedComponent.type;
    }
  },

我在 DOM 中得到以下输出

{__ob__: Observer}
loop: (...)
name: (...)
playbackRate: (...)
volume: (...)
__ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
get loop: ƒ reactiveGetter()
set loop: ƒ reactiveSetter(newVal)
get name: ƒ reactiveGetter()
set name: ƒ reactiveSetter(newVal)
get playbackRate: ƒ reactiveGetter()
set playbackRate: ƒ reactiveSetter(newVal)
get volume: ƒ reactiveGetter()
set volume: ƒ reactiveSetter(newVal)
__proto__: Object

为什么不包含类型、名称和isEnabled?

在 Typescript 文档中,他们证明这应该可以工作

https://www.typescriptlang.org/docs/handbook/interfaces.html#extending-interfaces

【问题讨论】:

  • isEnabled:boolean, - 你有一个逗号,把分号放在你的界面中的任何地方
  • 谢谢,我改了,还是一样的问题。
  • 接口不向对象添加属性。接口的唯一目的是识别对象的形状。如果您没有自己添加这些属性,它们将不存在。
  • 对了,那我有点迷茫了,为什么可以用另一个接口扩展一个接口,目的是什么。
  • @Ohgod你为什么确定呢?打字稿手册说以下typescriptlang.org/docs/handbook/…他们使用square.color

标签: javascript typescript vue.js interface polymorphism


【解决方案1】:

这里有一些非常可疑的类型断言:

  _componentGroup: this.componentGroup as IComponentGroup,
  _focussedComponent: this.componentGroup.components[0] as IComponent,

这些只是声称对象属于特定类型,它们不会更改对象。因此,除非这些对象实际上属于该类型,否则它们实际上可能没有接口中定义的任何属性。

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 2016-05-08
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多