【问题标题】:Different return types on inherited classes继承类的不同返回类型
【发布时间】:2017-10-21 18:04:33
【问题描述】:

假设我有 A 类和 B 类。A 定义了 B 可能使用的所有东西。 A不知道B使用时某个回调参数可能是什么类型。所以在A中它们被定义为Object。

class A {

    private _on_user_selection:(selection:Object) => void = $.noop;

    set on_user_selection(fn:(selection:Object) => void) {
        if ($.isFunction(fn)) {
            this._on_user_selection = fn;
        }
    }
}

class B extends A {
    // ...
}

B 知道回调参数是什么。现在我必须在 B 中做什么,这样我才能像这样使用它:

let b = new B();
b.on_user_selection = (selection:SomeInterfaceDefindeSomewhere):void => {
    // ...
};

在这种情况下,上面的方法可以正常工作,但我想修复 B 中的回调返回类型,而不仅仅是它实际调用的位置。

【问题讨论】:

  • 不会覆盖工作?

标签: javascript class typescript interface callback


【解决方案1】:

您可以将A 设为通用:

class A<T> {
    private _on_user_selection: (selection: T) => void = $.noop;

    set on_user_selection(fn: (selection: T) => void) {
        if ($.isFunction(fn)) {
            this._on_user_selection = fn;
        }
    }
}

class B extends A<SomeInterfaceDefindeSomewhere> {
    // ...
}

另外,请勿使用 Objectinstead use anynew object type 类型。

【讨论】:

  • 太好了,正是我想要的!谢谢:)
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
相关资源
最近更新 更多