typescript方法覆盖不起作用

时间:2017-11-19 10:54:47

标签: javascript class typescript override

我有一个基类A和一个扩展的类B,它覆盖了A的fetch方法。 但是,当我调用B.fetch()时,它会记录'baseclass'。为什么不调用B中定义的方法定义?

     class A {
        protected apiPath: string = ''
        static async fetch (id = null, Model = this, apiPath = this.apiPath): Promise<any> {
            console.log('basefetch')
            let url = apiPath
            if(id) url += '/' + id
            let { data } = await axios.get(url)
            let item: any = new Model(data)
            return item
        }
    }

    class B extends A {
        static async fetch(id = null, Model = this, apiPath = this.apiPath): Promise<Data> {
            console.log('childfetch')
            let {data} = await axios.get(apiPath)
            if (typeof data.challenge.participating == 'undefined') {
                data.challenge.participating = null
            }
            if (typeof data.challenge.progress == 'undefined') {
                data.challenge.progress = null
            }
            return new Model(data)
        }

class SomeOtherModule {
    async doSomething() {
        let b: B = await B.fetch()
    }
}

2 个答案:

答案 0 :(得分:1)

方法签名不同。在A中,您将返回Promise<any>,但在B中,您将返回Promise<Data>

您可以在this snippet中看到您尝试做的事情当然可以发挥作用:

class A {
  static fetch (): string {
    return 'basefetch';
  }
}

class B extends A {
  static fetch(): any {
    return 'childfetch';
  }
}

let aVal: string = A.fetch();
console.log(`aVal: ${aVal}`);

let bVal: string = B.fetch();
console.log(`bVal: ${bVal}`);

答案 1 :(得分:0)

将静态成员分配给构造函数。您必须将其称为B.fetch(...)

您的示例类的结果js代码:

var A = (function () {
    function A() {
    }
    A.fetch = function () {
        console.log("A fetch");
    };
    return A;
}());
var B = (function (_super) {
    tslib_1.__extends(B, _super);
    function B() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    B.fetch = function () {
        console.log("B fetch");
    };
    return B;
}(A));

这意味着您拨打了A.fetch(...)